问题
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