C# Thread 執行緒(執行序) 控制 開始/暫停/恢復/停止 的方法

C# Thread 執行緒(執行序) 控制 開始/暫停/恢復/停止 的方法

C# Thread 執行緒(執行序) 控制 開始/暫停/恢復/停止 的方法


資料來源: https://dotblogs.com.tw/AlexWang/2016/10/03/124332


Code:

public class ThreadWorker
{
	Thread _thread;
	ManualResetEvent _shutdownEvent;
	ManualResetEvent _pauseEvent;

	public void ThreadJob()
	{
		while (true)
		{
			// pause event : if WaitHandle is false, it will wait and return false
			_pauseEvent.WaitOne(Timeout.Infinite);
			// stop event
			if (_shutdownEvent.WaitOne(0)) break;

			// work here
			Console.WriteLine(DateTime.Now);

			// like Thread.Sleep(1000), but higher efficiency
			SpinWait.SpinUntil(() => false, 1000);
		}

		Console.WriteLine("Work is completed or stopped");
	}
	
	public void Start()
	{
		Console.WriteLine("Add a new thread");
		_thread = new Thread(ThreadJob);
		_shutdownEvent = new ManualResetEvent(false);
		_pauseEvent = new ManualResetEvent(true);

		_thread.IsBackground = true;
		_thread.Start();
	}

	public void Pause()
	{
		// Set WaitHandle false
		_pauseEvent.Reset();
	}

	public void Resume()
	{
		// Set WaitHandle true
		_pauseEvent.Set();
	}

	public void Stop()
	{
		// trigger stop
		_shutdownEvent.Set();
		// if thread suspend, let it resume.
		_pauseEvent.Set();
		_thread.Join();
		_thread = null;
	}
}

class Program
{
	static void Main(string[] args)
	{
		ThreadWorker _threadWorker = new ThreadWorker();

		Console.WriteLine("[Start 5s]");
		_threadWorker.Start();
		Thread.Sleep(5000);

		Console.WriteLine("[Pause 10s]");
		_threadWorker.Pause();
		Thread.Sleep(10000);

		Console.WriteLine("[Resume 3s]");
		_threadWorker.Resume();
		Thread.Sleep(3000);

		Console.WriteLine("[Stop]");
		_threadWorker.Stop();
		Thread.Sleep(5000);

		Console.WriteLine("[Start again 3s]");
		_threadWorker.Start();
		Thread.Sleep(3000);

		Console.WriteLine("[Pause 3s]");
		_threadWorker.Pause();
		Thread.Sleep(3000);

		Console.WriteLine("[Resume 2s]");
		_threadWorker.Resume();
		Thread.Sleep(2000);

		Console.WriteLine("[Stop]");
		_threadWorker.Stop();

		Console.ReadKey();
	}
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *