How to cancel an asynchronous call? The .NET APM doesn\'t seem to support this operation.
I have the following loop in my code which spawns multiple threads on the Threa
A "cancel flag" is the way to do it, though not a global one, necessarily. The unavoidable point is that you need some way to signal to the thread that it should stop what it's doing.
In the case of BeginInvoke
, this is hard to do with anything but a global flag, because the work is carried out on the threadpool, and you don't know which thread. You have a couple of options (in order of preference):
BackgroundWorker
instead of BeginInvoke
. This has cancellation functionality baked-in. This has other benefits, like progress monitoring, and "Work complete" callbacks. It also nicely handles exceptions.ThreadPool.QueueUserWorkItem
, passing in an object as the state that has a Cancel()
method that sets a Cancelled
flag that the executing code can check. Of course you'll need to keep a reference to the state object so you can call Cancel()
on it (which is something the BackgroundWorker
does for you - you have a component on your form. (Thanks to Fredrik for reminding about this).ThreadStart
delegate, passing in a state object as with option 2.