C# 是否可以中断 ThreadPool 内的特定线程?

发布于 2024-08-24 11:27:53 字数 530 浏览 5 评论 0原文

假设我已将一个工作项放入 ThreadPool 中排队,但如果没有要处理的数据(从 BlockingQueue 读取),该工作项就会阻塞。如果队列是空的并且不会有更多的工作进入队列,那么如果我想中断阻塞任务,我必须调用 Thread.Interrupt 方法,但是如何做同样的事情使用ThreadPool

代码可能如下所示:

void Run()
{
    try
    {
        while(true)
        {
            blockingQueue.Dequeue();
            doSomething();
        }
    }
    finally
    {
        countDownLatch.Signal();
    }
}

我知道在这种情况下最好的办法是使用常规的Thread,但我想知道是否有ThreadPool中断工作项的等效方法。

Suppose that I've queued a work item in a ThreadPool, but the work item blocks if there is no data to process (reading from a BlockingQueue). If the queue is empty and there will be no more work going into the queue, then I must call the Thread.Interrupt method if I want to interrupt the blocking task, but how does one do the same thing with a ThreadPool?

The code might look like this:

void Run()
{
    try
    {
        while(true)
        {
            blockingQueue.Dequeue();
            doSomething();
        }
    }
    finally
    {
        countDownLatch.Signal();
    }
}

I'm aware that the best thing to do in this situation is use a regular Thread, but I'm wondering if there is a ThreadPool equivalent way to interrupt a work item.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烂人 2024-08-31 11:27:53

那是哪个 BlockingQueue ?这是BCL课程吗? TPL类?还是定制?

不管;很简单——我不会。您可以在线程生命周期的早期做一些事情来存储线程引用,但我根本不会使用ThreadPool来完成这项工作,因为听起来它运行的时间更长。常规的Thread似乎更合适。

我还感到惊讶的是,没有内置方法告诉队列释放所有工作人员 - 我之前编写过阻塞队列,并且我倾向于使用该模式(例如, 从这里):

public bool TryDequeue(out T value) {...}

这样:

  • 如果存在数据
  • 阻塞,则立即返回 true ,并且(最终)如果存在则返回 true没有数据,但有些数据会被添加
  • 阻塞,并且(最终)如果队列被关闭则返回 false

Which BlockingQueue is that? Is that a BCL class? TPL class? Or custom?

No matter; simply - I wouldn't. You could do something early in the thread's life to store the thread reference, but I simply wouldn't use the ThreadPool for this job as it sounds like it is longer running. A regular Thread would seem more appropriate.

I'm also surprised that there is no inbuilt method of telling the queue to release all the workers - I've written blocking queues before, and I tend to use the pattern (for example, from here):

public bool TryDequeue(out T value) {...}

with this:

  • returning true immediately if there is data
  • blocking and (eventually) returning true if there isn't data but some is added
  • blocking and (eventually) returning false if the queue is being shut down
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文