简体   繁体   English

线程暂停并恢复c#

[英]Threads pausing and resuming c#

I've got several threads ,how can I pause/resume them? 我有几个线程,我怎么能暂停/恢复它们?


From duplicate question: 从重复的问题:

How can i pause 5 threads, and to remember their status. 我如何暂停5个线程,并记住它们的状态。 Because one of them is eating another is thinking, etc. 因为其中一个正在吃另一个正在思考等等

If you're using System.Threading.Thread , then you can call Suspend and Resume . 如果您正在使用System.Threading.Thread ,则可以调用SuspendResume This, however is not recommended. 但不建议这样做。 There's no telling what a thread might be doing when you call Suspend . 当你调用Suspend时,没有人知道线程可能在做什么。 If you call Suspend while the thread holds a lock, for example, or has a file open for exclusive access, nothing else will be able to access the locked resource. 例如,如果在线程持有锁定时调用Suspend ,或者打开一个文件进行独占访问,则其他任何内容都无法访问锁定的资源。

As the documentation for Thread.Suspend says: 正如Thread.Suspend的文档所说:

Do not use the Suspend and Resume methods to synchronize the activities of threads. 不要使用Suspend和Resume方法来同步线程的活动。 You have no way of knowing what code a thread is executing when you suspend it. 暂停它时,您无法知道线程正在执行的代码。 If you suspend a thread while it holds locks during a security permission evaluation, other threads in the AppDomain might be blocked. 如果在安全权限评估期间挂起线程时挂起线程,则可能会阻止AppDomain中的其他线程。 If you suspend a thread while it is executing a class constructor, other threads in the AppDomain that attempt to use that class are blocked. 如果在执行类构造函数时挂起线程,则会阻止AppDomain中尝试使用该类的其他线程。 Deadlocks can occur very easily. 死锁很容易发生。

Typically, you control threads' activity using synchronization primitives like events. 通常,您使用事件等同步原语来控制线程的活动。 A thread will wait on an event (look into AutoResetEvent and ManualResetEvent ). 线程将等待事件(查看AutoResetEventManualResetEvent )。 Or, if a thread is servicing a queue, you'll use something like BlockingCollection so that the thread can wait for something to be put into the queue. 或者,如果一个线程正在为队列服务,你将使用类似BlockingCollection东西,这样线程就可以等待将某些东西放入队列。 All of these non-busy wait techniques are much better than arbitrarily suspending and restarting a thread, and don't suffer from the potential disastrous consequences. 所有这些非繁忙等待技术都比任意暂停和重新启动线程要好得多,并且不会遭受潜在的灾难性后果。

You have to use synchronisation techniques 您必须使用同步技术

MSDN Thread Synchronization MSDN线程同步

Have a look at Monitor.Wait and Monitor.Pulse in the first instance- Marc Gravell has a nice example used in a queue here . 在第一个实例中看看Monitor.WaitMonitor.Pulse- Marc Gravell 在这里有一个很好的例子

In it quite likely that you want to consider using a Producer/Consumer queue. 您很可能想要考虑使用Producer / Consumer队列。

In the main thread: 在主线程中:

ManualResetEvent re = new ManualResetEvent(true);

In all the threads, at "strategic" points: 在所有线程中,在“战略”点:

re.WaitOne();

In the main thread, to stop the threads: 在主线程中,要停止线程:

re.Reset();

and to restart: 并重新启动:

re.Set();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM