4

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.

H H
  • 263,252
  • 30
  • 330
  • 514
Tirmit
  • 183
  • 1
  • 3
  • 15
  • 8
    If you think you need to Pause threads, you've got problems you're not aware of. – H H Feb 19 '11 at 19:54

5 Answers5

15

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.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
2

You have to use synchronisation techniques

MSDN Thread Synchronization

Community
  • 1
  • 1
  • That document is very old -- 2005. As other answers mentioned, you probably want to use threadsafe queues or some such to achieve your actual goal, rather than adding a layer of arbitrary and error prone synchronization with event wait primitives. – Tom A Mar 14 '13 at 00:24
  • http://stackoverflow.com/questions/10721148/how-to-implement-thread-safe-queues is a pretty good recap of the topic – Bryan Devaney Apr 04 '13 at 15:44
2

Have a look at Monitor.Wait and Monitor.Pulse in the first instance- Marc Gravell has a nice example used in a queue here.

In it quite likely that you want to consider using a Producer/Consumer queue.

Community
  • 1
  • 1
RichardOD
  • 28,883
  • 9
  • 61
  • 81
1

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();
xanatos
  • 109,618
  • 12
  • 197
  • 280