Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public abstract class Server : IDisposable
- {
- public void Dispose()
- {
- Stop();
- }
- public void Start()
- {
- if (IsRunning)
- throw new Exception("Cannot start while running");
- MyThread = new Thread(Run);
- BeforeStart();
- MyThread.Start();
- AfterStart();
- }
- public void Stop(bool shouldWait = true)
- {
- if (!IsRunning)
- return;
- BeforeStop();
- ShouldBeRunning = false;
- MyThread.Interrupt();
- if (shouldWait)
- Wait();
- }
- public void Wait()
- {
- BeforeJoin();
- MyThread.Join();
- AfterJoin();
- }
- protected virtual void BeforeStart()
- {
- }
- protected virtual void AfterStart()
- {
- }
- protected virtual void BeforeStop()
- {
- }
- protected virtual void BeforeJoin()
- {
- }
- protected virtual void AfterJoin()
- {
- }
- protected virtual void AfterCycle()
- {
- }
- protected virtual void BeforeCycle()
- {
- }
- protected abstract void RunSingleIteration();
- protected virtual void Run()
- {
- IsRunning = true;
- BeforeCycle();
- while (ShouldBeRunning)
- {
- try
- {
- RunSingleIteration();
- }
- catch (ThreadInterruptedException)
- {
- continue;
- }
- }
- AfterCycle();
- IsRunning = false;
- }
- public bool ShouldBeRunning { get; set; } = true;
- public bool IsRunning { get; protected set; } = false;
- private Thread MyThread { get; set; }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement