Ted Carron

I am using a 'BackgroundWorker' object to impliment multithreadeding because it provides a really neat way of passing events into the main UI thread.

My problems occur when it is time to halt the background worker thread.

I can easily signal the thread to exit via synchronization objects and if desired I can service the 'RunWorkerCompleted' event later on but what I can NOT neatly do is wait for the thread to exit after I have signalled it to do so.

If this was a thread I had instantiated myself I could call its 'Join' method but I can find no equivalent for the BackgroundWorker - nor can I see anyway to get hold of its thread to call join on it myself.

I can bodge something up using synchronization objects so that the thread loop releases an object just before it exits and the terminating function 'Waits' on this object. But this approach causes problems during debug.

Is there any way to perform a 'Join' or some equivalent operation on a background worker thread.

Thanks in advance for any help or discussion on this subject.


Re: .NET Base Class Library How do you 'Join' a background worker thread?

Peter Ritchie

The thread uses for the BackgroundWorker DoWork event handler is pulled from the thread pool. Even if you could get a hold of that to use Join, that thread could have been reused by something else and you'd end up waiting on the wrong thread.

The Join pattern is usually used for parallel processing (concurrency) where you want to break work up into logical chunks into two or more threads, where continuation is dependant on the result of all those threads. BackgroundWorker is used to perform lengthy operations on thread other than the UI thread.

I assume you'd be calling Thread.Join on the GUI thread, which really defeats the purpose of using BackgroundWorker.

Re: .NET Base Class Library How do you 'Join' a background worker thread?


You could just loop and Sleep() until BackgroundWorker.IsBusy returns false. Crude but equivalent to calling Thread.Join().

Re: .NET Base Class Library How do you 'Join' a background worker thread?

Joannes Vermorel - MSP

I would maybe not go to far into that direction because weird things can happen if you end-up with several threads waiting for the termination of the background worker.

For example, if the BackgroundWorker is (regularly) restarted, then you might have a thread that never Join() although the BackgroundWorker terminates on a regular basis.

Hope it helps,
Lokad.com, sales forecasting