开发者

Threads pausing and resuming c#

I've got se开发者_JAVA百科veral 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.


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.


You have to use synchronisation techniques

MSDN Thread Synchronization


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();


You can use Suspend() and Resume().
http://msdn.microsoft.com/en-us/library/system.threading.thread.resume.aspx
http://msdn.microsoft.com/en-us/library/system.threading.thread.suspend.aspx
You can also read:
What are alternative ways to suspend and resume a thread?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜