问题描述
我如何中止,暂停和在C#中恢复线程
How do I abort, pause and resume threads in C#?
相关问题:
有没有办法无限期暂停一个线程?
推荐答案
在一般情况下,不要暂停(或中止)一个发
- 您无法正常告诉它在做什么,而这可能会导致各种各样的锁定问题,如一个锁没有释放,或者一个类型初始化(静态构造函数),它是。左挂
In general, don't pause (or abort) a Thread
- you can't normally tell what it was doing, and this could lead to all sorts of locking issues, such as an a lock that isn't released, or a type initializer (static constructor) that is left hanging.
您可能,但是,通过更优雅的方式暂停代码 - 例如,使用的ManualResetEvent
中您的循环外部代码(在另一个线程),可以打开和关闭:
You might, however, pause code through more elegant methods - for example, using a ManualResetEvent
in your loop that external code (on another thread) can open and close:
// worker loop
while(alive) {
// if the gate is closed, wait up to 5 seconds; if still not
// open, go back to the loop-start to re-check "alive"
if (!gate.WaitOne(5000)) continue;
// do work...
}
然后访问(可能是间接的),另一个线程可以暂停(重置
)和resume(设置
)的工人,但在知识,它只有在安全的状态下暂停。
Then another thread with access (probably indirect) can pause (Reset
) and resume (Set
) the worker, but in the knowledge that it only pauses in a safe state.
重新您的评论(另一回复) - 这听起来像你有一个读写器;理想的生产者/消费者场景。我对如何写一个上限尺寸生产者/消费者这个问题一个例子(所以不会如果消费者运行慢)淹没。 - 如果不存在数据,以及生产者的块,如果有太多的消费者块
这篇关于我如何中止,暂停和在C#中恢复线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!