backgroundworker: How do I execute a method and support canceling _DoWork?
I have referred to MSDN and found out that it is quite easy to cancel a BackgroundWorker's _DoWork(), by trigger an e开发者_高级运维vent.
I would like to know how to cancel _DoWork() while performing work in another method that I've called within _DoWork().
Is this possible?
http://pastebin.com/wHrrBWKZ
Thanks,
Matt
The BackgroundWorker
sample here shows how to do it.
In summary:
- When you create the
BackgroundWorker
, setWorkerSupportsCancellation
. - In your
DoWork
handler, periodically checkCancellationPending
. If it is true, then setDoWorkEventArgs.Cancel
to true and return fromDoWork
. - To cancel the task, call
CancelAsync
. - To detect the task has been cancelled, observe
RunWorkerCompletedEventArgs.Cancelled
.
To do this from within another method, that method must have the BackgroundWorker
instance and the DoWorkEventArgs
instance passed to it.
精彩评论