tags:

views:

240

answers:

2

I want to implement a timeout on the execution of tasks in a project that uses the CCR. Basically when I post an item to a Port or enqueue a Task to a DispatcherQueue I want to be able to abort the task or the thread that its running on if it takes longer than some configured time. How can I do this?

+2  A: 

Can you confirm what you are asking? Are you running a long-lived task in the Dispatcher? Killing the thread would break the CCR model, so you need to be able to signal to the thread to finish its work and yield. Assuming it's a loop that is not finishing quick enough, you might choose to enqueue a timer:

var resultTimeoutPort = new Port<DateTime>();
dispatcherQueue.EnqueueTimer(TimeSpan.FromSeconds(RESULT_TIMEOUT), 
                             resultTimeoutPort);

and ensure the blocking thread has available a reference to resultTimeoutPort. In the blocking loop, one of the exit conditions might be:

do
{
    //foomungus amount of work
}while(resultTimeoutPort.Test()==null&&
       someOtherCondition)

Please post more info if I'm barking up the wrong tree.

spender
You're heading in the right direction except that I was trying to avoid having to make changes the foomungus work code. Also that code may not always have a loop sometimes I just want it to try and complete in time t and go away if it can't. I've been doing some reading and it looks like there may not be a way to get the exact behavior I want because I would be breaking the model as you've said.
SpaceghostAli
Indeed, without killing a thread, I think you're stuck with signalling to it to bail quickly. What are you trying to achieve? Perhaps there's a different way of tackling the problem?
spender
A: 

You could register the thread (Thread.CurrentThread) at the beginning of your CCR "Receive" handler (or in a method that calls your method via a delegate). Then you can do your periodic check and abort if necessary basically the same way you would have done it if you created the thread manually. The catch is that if you use your own Microsoft.Ccr.Core.Dispatcher with a fixed number of threads, I don't think there is a way to get those threads back once you abort them (based on my testing). So, if your dispatcher has 5 threads, you'll only be able to abort 5 times before posting will no longer work regardless of what tasks have been registered. However, if you construct a DispatcherQueue using the CLR thread pool, any CCR threads you abort will be replaced automatically and you won't have that problem. From what I've seen, although the CCR dispatcher is recommended, I think using the CLR thread pool is the way to go in this situation.

Ike