Advertisement
Ultimga

ThreadWorker

Nov 12th, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | None | 0 0
  1. using System.Threading;
  2.  
  3. namespace Swordfish {
  4. namespace threading
  5. {
  6.  
  7. public class ThreadWorker
  8. {
  9.     private volatile bool stop = false;
  10.     private volatile bool pause = false;
  11.  
  12.     private Thread thread = null;
  13.  
  14.     public ThreadWorker()
  15.     {
  16.         thread = new Thread(Tick);
  17.     }
  18.  
  19.     public void Start()
  20.     {
  21.         stop = false;
  22.         pause = false;
  23.         thread.Start();
  24.     }
  25.  
  26.     public void Stop()
  27.     {
  28.         stop = true;
  29.     }
  30.  
  31.     public void Restart()
  32.     {
  33.         stop = false;
  34.         pause = false;
  35.         thread.Abort();
  36.         thread.Start();
  37.     }
  38.  
  39.     public void Pause()
  40.     {
  41.         pause = true;
  42.     }
  43.  
  44.     public void Unpause()
  45.     {
  46.         pause = false;
  47.     }
  48.  
  49.     public void TogglePause()
  50.     {
  51.         pause = !pause;
  52.     }
  53.  
  54.     public void Kill()
  55.     {
  56.         thread.Abort();
  57.     }
  58.  
  59.     private void Tick()
  60.     {
  61.         while (stop == false)
  62.         {
  63.             while (pause == false)
  64.             {
  65.                 Run();
  66.             }
  67.  
  68.             Thread.Sleep(200);  //  Sleep when paused
  69.         }
  70.  
  71.         //  Stopped thread safely
  72.     }
  73.  
  74.     public virtual void Run() {}
  75. }
  76.  
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement