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