C# 是否可以中断 ThreadPool 内的特定线程?
假设我已将一个工作项放入 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那是哪个
BlockingQueue
?这是BCL课程吗? TPL类?还是定制?不管;很简单——我不会。您可以在线程生命周期的早期做一些事情来存储线程引用,但我根本不会使用
ThreadPool
来完成这项工作,因为听起来它运行的时间更长。常规的Thread
似乎更合适。我还感到惊讶的是,没有内置方法告诉队列释放所有工作人员 - 我之前编写过阻塞队列,并且我倾向于使用该模式(例如, 从这里):
这样:
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 regularThread
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):
with this: