場景:
開發過程中遇到這樣一個需求:需要定時的進行一些操作,同時這個定時時間是可以隨時變動的,這個任務是可以啟停的。第一反應是用線程。
實現:
這里由於需求少,就手動添加了幾個線程,實際上多的話可以用線程池。
添加每個線程的ManualResetEvent事件:ManualResetEvent中可以傳入初始狀態
private static ManualResetEvent _threadOne = new ManualResetEvent(true);
逐一添加線程:
Thread thread = new Thread(() => { int i = 1; var random = new Random(); while ( true ) { if ( !_isOpen[0] ) { // 阻塞本身線程 _threadOne.Reset(); _threadOne.WaitOne(); } // do something } }); thread.IsBackground = true; thread.Start();
這里的Reset()就是使ManualResetEvent所在的線程處於非終止狀態,而WaitOne()就是處於阻塞並且等待新的狀態信號。
終止狀態下,線程可以訪問waitone()下的代碼;非終止,則無法訪問。
恢復線程:由於這個時候線程已經被暫停,需要在其他線程修改該線程狀態
_isOpen[0]=true;
_threadOne.Set();
暫停線程:
_isOpen[0]=false;
參考:
https://www.cnblogs.com/li-peng/p/3291306.html
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread?view=net-6.0#Properties
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.manualresetevent?view=net-6.0