1. 程式人生 > 其它 >c# 主執行緒控制其他執行緒的暫停和恢復

c# 主執行緒控制其他執行緒的暫停和恢復

場景:

  開發過程中遇到這樣一個需求:需要定時的進行一些操作,同時這個定時時間是可以隨時變動的,這個任務是可以啟停的。第一反應是用執行緒。

實現:

  這裡由於需求少,就手動添加了幾個執行緒,實際上多的話可以用執行緒池。

  新增每個執行緒的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