Can I kill a BackgroundWorker thread?

Is it possible to β€œkill” a BackgroundWorker thread?

In my DoWork event, I can’t check the cancel flag, because I have a call blocking the external COM interface or querying the database. CancelAsync does not cancel the COM call.

How can I do this, please? Any suggestions would be much appreciated.

Thanks in advance.

+6
multithreading backgroundworker
source share
2 answers

I don't know about a safe way to interrupt a thread.

The background worker can check if he should cancel and cancel himself, but if he does not request a database, you cannot make it until it returns.

You can work on a ThreadPool thread and just drop the thread and start another if it is no longer needed (make sure that when it comes back from the db request, it checks to cancel it before doing anything unpleasant). Of course, you need to balance performance and manage thread synchronization. If you go down this path, you can take a look at the static Interlocked class to effectively lock the critical section.

+1
source share

No, you cannot kill the BackgroundWorker thread, you can only cancel it, as you noticed, but it needs some interaction with the background thread: "Work code should periodically check CancellationPending to see if it is set to true." (c) MSDN

If you need full control over a thread, you will need to create it yourself using the Thread class.

+3
source share

All Articles