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. Because one of them is eating another is thinking, etc.
If you're using System.Threading.Thread
, then you can call Suspend
and Resume
. This, however is not recommended. There's no telling what a thread might be doing when you call 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.
As the documentation for Thread.Suspend says:
Do not use the Suspend and Resume methods to synchronize the activities of threads. 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. 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. 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
). 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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With