我如何中止,暂停和在C#中恢复线程? [英] How do I abort, pause and resume threads in C#?

查看:98
本文介绍了我如何中止,暂停和在C#中恢复线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何中止,暂停和在C#中恢复线程

How do I abort, pause and resume threads in C#?

相关问题:

<一个HREF =http://stackoverflow.com/questions/142826/is-there-a-way-to-indefinitely-pause-a-thread>有没有办法无限期暂停一个线程?

推荐答案

在一般情况下,不要暂停(或中止)一个 - 您无法正常告诉它在做什么,而这可能会导致各种各样的锁定问题,如一个锁没有释放,或者一个类型初始化(静态构造函数),它是。左挂

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.


重新您的评论(另一回复) - 这听起来像你有一个读写器;理想的生产者/消费者场景。我对如何写一个上限尺寸生产者/消费者这个问题一个例子(所以不会如果消费者运行慢)淹没。 - 如果不存在数据,以及生产者的块,如果有太多的消费者块

Re your comment (on another reply) - it sounds like you have a reader and writer; ideal for a producer/consumer scenario. I have a an example on this question of how to write a producer/consumer with a capped size (so it won't swamp if the consumer runs slow) - the consumer blocks if there is no data, and the producer blocks if there is too much.

这篇关于我如何中止,暂停和在C#中恢复线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆