views:

239

answers:

1

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.

+2  A: 

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
Marc Gravell
+1 TryDequeue is a very good solution to the problem.
Lirik
A non-volatile boolean variable (closing) tested in a short loop, does that always work?
Hans Passant
@nobugz - I *believe* the `Monitor.Wait` will force a refresh; interesting question though.
Marc Gravell
Lock statement: yes, due to try block. Monitor.Wait(), very doubtful. It would require the JIT to detect specific methods.
Hans Passant
@nobugz note that `Wait` calls into `ObjWait` which is `internalcall`, so it isn't entirely up to the JIT; but I might throw this open as a question.
Marc Gravell
@nobugz - raised here: http://stackoverflow.com/questions/2431238/does-monitor-wait-ensure-that-fields-are-re-read
Marc Gravell