C#是否可以中断ThreadPool中的特定线程? [英] C# Is it possible to interrupt a specific thread inside a ThreadPool?

查看:781
本文介绍了C#是否可以中断ThreadPool中的特定线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



代码可能如下所示:

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

我知道最好的事情这种情况是使用一个常规的线程,但我想知道是否有一个 ThreadPool 等效的方式来中断一个工作 c> c> c> 是BCL类吗? TPL类?还是定制?



简单 - 我不会。你可以在线程的生命早期做一些事来存储线程引用,但我不会使用 ThreadPool 这个工作,因为它听起来喜欢它更长的运行。



我还感到惊讶的是没有内置的方法来告诉队列释放所有的工人 - 我之前写过阻塞队列,我倾向于使用模式(例如, from this ):

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




  • 如果有数据则立即返回true

  • 阻止并且如果没有数据则返回true

  • 阻止和(最终)如果队列正在关闭则返回false


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.

解决方案

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

这篇关于C#是否可以中断ThreadPool中的特定线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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