C# Is it possible to interrupt a specific thread inside a ThreadPool?

可紊 提交于 2019-12-10 19:48:52

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/2430609/c-sharp-is-it-possible-to-interrupt-a-specific-thread-inside-a-threadpool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!