问题描述
我有几个线程,我怎么可以暂停/恢复呢?
I've got several threads ,how can I pause/resume them?
这是重复的问题:
我怎样才能暂停5个线程,而且要记住它们的状态。因为他们中的一个是吃又是思想,等等。
How can i pause 5 threads, and to remember their status. Because one of them is eating another is thinking, etc.
推荐答案
如果您使用的是 System.Threading.Thread
,那么你可以调用暂停
和恢复
。这,但是不推荐使用。有没有说什么线程可能会做,当你调用暂停
。如果你调用暂停
,而线程持有的锁,例如,或打开的文件以独占访问,不出意外将能够访问锁定的资源。
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.
对于文档Thread.Suspend说:
不要使用挂起和恢复 方法来同步活动 线程。你有没有办法知道 什么$ C C线程$正在执行时, 你将其挂起。如果暂停 线程同时持有期间锁 安全许可评价,其他 在AppDomain中的线程可能会 受阻。如果您挂起一个线程,而 它在执行类的构造函数, 在AppDomain中的其他线程 尝试使用该类被封锁。 死锁极易发生。
通常情况下,你使用的同步原语类似事件控制线程的活动。一个线程等待一个事件(看看的AutoResetEvent
和的ManualResetEvent
)。或者,如果一个线程正服务队列,你会使用类似 BlockingCollection
这样的线程可以等待的东西被放入队列。所有这些非忙等待技术是不是随意暂停和重新启动一个线程要好得多,并没有从潜在的灾难性后果受苦。
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.
这篇关于线程暂停和恢复C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!