BackgroundWorker CancelSync() ??
-
Was just whipping up a quick util which immediately executes an assembly normally run by a winservice at night. The assembly implements an interface exposing a DoWork() function. I decided to play with the BackgroundWorker component to keep my utils UI responsive and show a little animation while it chugs along. So I have a worker class which essentially implements the interface and calls DoWork(). I thought it would be cool to implement a cancel button while I was at it. BackgroundWorker supports a CancelAsync() which requires the worker thread to check backgroundWorker.CancellationPending and then return. But what if my worker is calling in to an assembly which is performing the long process? Just curious if there is a way to forcing a BackgroundWorker to immediately cancel. A call to Dispose() was ignored and I didn't see a way to force the thread to exit immediately.
-
Was just whipping up a quick util which immediately executes an assembly normally run by a winservice at night. The assembly implements an interface exposing a DoWork() function. I decided to play with the BackgroundWorker component to keep my utils UI responsive and show a little animation while it chugs along. So I have a worker class which essentially implements the interface and calls DoWork(). I thought it would be cool to implement a cancel button while I was at it. BackgroundWorker supports a CancelAsync() which requires the worker thread to check backgroundWorker.CancellationPending and then return. But what if my worker is calling in to an assembly which is performing the long process? Just curious if there is a way to forcing a BackgroundWorker to immediately cancel. A call to Dispose() was ignored and I didn't see a way to force the thread to exit immediately.
There isn't a way, no. You can terminate the thread via Thread.Abort, but that's generally a bad idea since it can leave your code in a volatile, unstable state. I recommend having your background worker spawn a new thread in the DoWork handler. Have that thread do the actual work, while the DoWork thread do 2 things: continually check for the cancel flag, and continually watch for completion of the spawned thread. When either the spawned thread finishes or the cancel flag is true, your DoWork thread can return, thus your RunWorkerCompleted handler will be fired. p.s. check out Roy Osherove's extended BackgroundWorker[^], which includes a
CancelImmediately()
method that accomplishes pretty much what you're trying to do.Tech, life, family, faith: Give me a visit. I'm currently blogging about: God-as-Judge, God-as-Forgiver The apostle Paul, modernly speaking: Epistles of Paul Judah Himango