Topics that pause and resume C #

I have several threads, how can I pause / resume them?


From a repeating question:

How can I pause 5 threads and remember their status. Because one of them eats another, thinks, etc.

+4
source share
5 answers

If you use System.Threading.Thread , you can call Suspend and Resume . This, however, is not recommended. It does not say what the thread can do when you call Suspend . If you call Suspend when a thread holds a lock, for example, or has a file open for exclusive access, nothing else will be able to access the blocked resource.

As the documentation for Thread.Suspend says:

Do not use Pause and Resume methods to synchronize threads. You have no way of knowing what code the thread is executing when you pause it. If you pause while it holds a lock while evaluating security permissions, other threads in the AppDomain may be blocked. If you pause a thread while it is executing a class constructor, other threads in the AppDomain that attempt to use this class are blocked. Dead ends can occur very easily.

Typically, you control thread activity using synchronization primitives, such as events. The thread will wait for the event (see AutoResetEvent and ManualResetEvent ). Or, if the thread is serving the queue, you will use something like BlockingCollection so that the thread can wait for something to be queued. All these idle wait methods are much better than arbitrarily pausing and restarting a thread, and do not suffer from possible catastrophic consequences.

+15
source

You must use synchronization methods

MSDN Thread Sync

+2
source

Take a look at Monitor.Wait and Monitor.Pulse in the first case - Mark Gravel has a good example used in the queue here .

It is likely that you want to consider using the Producer / Consumer queue.

+2
source

In the main thread:

 ManualResetEvent re = new ManualResetEvent(true); 

In all flows in the "strategic" points:

 re.WaitOne(); 

In the main thread, to stop the threads:

 re.Reset(); 

and restart:

 re.Set(); 
+1
source

Source: https://habr.com/ru/post/1340476/


All Articles