Posted By: exoteric | Oct 26th @ 1:12 PM
page 1 of 1
Comments: 8 | Views: 154
exoteric
exoteric
I : Next<I>

What is the best practice for thread pre-emption/cancellation? I have the following scenario: (And do not yet use Parallel Extensions for .Net)

 

An external service call often takes a long time to complete (as little as 1 second and as high as 10+ seconds). This brings an unacceptable latency down to the UI layer (the UI is in a different application using a web service component written in .Net using COM interop.) Anyway, the base problem is a single call which has a variable latency and the code cannot be granularized further as the latency is external.

 

So clearly the call needs to take place asynchronously. This is now almost implemented. The problem then arises, what to do with cancellation. If the code was fine-grained it would be possible to make it regularly read a cancellation state variable. This is not the case - the call is "monolithic" - so such a variable cannot be used. Then looking at the Thread API there is a method called Abort(). Absent a brutal sounding method like Kill() (which would obviously also be evil), I expect this to be the suitable method for this scenario. Right or?

 

I use a "synchronization counter" to ensure the worker thread doesn't modify the environment if it accidentally completes post-cancellation.

Thread.Abort is really just a badly named version of Thread.KillWithExtremePrejudiceBreakingExceptionHandlingWhilstYouDo, you probably don't ever want to call it unless you really have to.

 

http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation

I'm not really clear about why you can't use an abort bool and just check it periodically during the code (it's not tidy, but it works). Unless you're saying you have a call that takes a long time, which you may want to cancel before it completes but you have no control over the function. If so, the usual approach is to just let the function complete and then check afterwards whether or not the result should stand or whether it should simply be abandoned as the result of a cancellation. Obviously that requires the use of a thread pool or similar to prevent a thread that would be cancelled from preventing further operation.

Yeah, I first came across that solution when I was looking into how web browsers dealt with HTTP POSTs, pretty much all of them do it in that way.

Just a note about Abort (I've been reading a lot about threading the past week or so): there's no guarantee that it will stop your thread immediately. It waits until things can be safely garbage-collected and then stops it.

 

I think that and just ignoring the result are your only real options if the function being called cannot be modified to support cancellation.

page 1 of 1
Comments: 8 | Views: 154
Microsoft Communities