Advertisement
RaWRCoder

Server

Oct 20th, 2015
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.95 KB | None | 0 0
  1. public abstract class Server : IDisposable
  2.     {
  3.         public void Dispose()
  4.         {
  5.             Stop();
  6.         }
  7.         public void Start()
  8.         {
  9.             if (IsRunning)
  10.                 throw new Exception("Cannot start while running");
  11.             MyThread = new Thread(Run);
  12.             BeforeStart();
  13.             MyThread.Start();
  14.             AfterStart();
  15.         }
  16.         public void Stop(bool shouldWait = true)
  17.         {
  18.             if (!IsRunning)
  19.                 return;
  20.             BeforeStop();
  21.             ShouldBeRunning = false;
  22.             MyThread.Interrupt();
  23.             if (shouldWait)
  24.                 Wait();
  25.         }
  26.  
  27.         public void Wait()
  28.         {
  29.             BeforeJoin();
  30.             MyThread.Join();
  31.             AfterJoin();
  32.         }
  33.  
  34.  
  35.         protected virtual void BeforeStart()
  36.         {
  37.         }
  38.  
  39.         protected virtual void AfterStart()
  40.         {
  41.         }
  42.         protected virtual void BeforeStop()
  43.         {
  44.         }
  45.         protected virtual void BeforeJoin()
  46.         {
  47.         }
  48.         protected virtual void AfterJoin()
  49.         {
  50.         }
  51.         protected virtual void AfterCycle()
  52.         {
  53.         }
  54.         protected virtual void BeforeCycle()
  55.         {
  56.         }
  57.  
  58.         protected abstract void RunSingleIteration();
  59.  
  60.         protected virtual void Run()
  61.         {
  62.             IsRunning = true;
  63.             BeforeCycle();
  64.             while (ShouldBeRunning)
  65.             {
  66.                 try
  67.                 {
  68.                     RunSingleIteration();
  69.                 }
  70.                 catch (ThreadInterruptedException)
  71.                 {
  72.                     continue;
  73.                 }
  74.             }
  75.             AfterCycle();
  76.             IsRunning = false;
  77.         }
  78.  
  79.         public bool ShouldBeRunning { get; set; } = true;
  80.         public bool IsRunning { get; protected set; } = false;
  81.         private Thread MyThread { get; set; }
  82.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement