views:

292

answers:

2

i am aborting a thread (will be threads soon enough) and the problem is i need to stall until all threads have been aborted. After doing theThread.Abort(); i thought of using theThread.Join() to wait until its been fully aborted. However that doesnt work. It just waits forever. How can i abort each thread and wait until its done before continuing?

If your curious why, in this case i am closing a window, i pass a delegate func into the thread which it calls when its done (or aborted). If i dont stall then the window will close and the function will call invalid handles/objs. I can easily use the same method, stick a flag in and loop & sleep until all flags are set but that doesnt feel right.

+4  A: 

I've learnt from many years experience with threads that there are a couple of rules that, if followed, make life a lot easier.

The one pertinent to this question is:

  • let threads control their own resources, including their lifetime.

I wouldn't abort a thread, I'd simply set up a communications method between the threads creator and the thread itself to signal the thread to terminate, and then let the thread itself shut down.

This method can often be as simple as a write-by-creator/read-by-thread flag which controls the threads main loop. If the thread has long running tasks while in the loop, you should also check periodically.

Then the creator thread should just join until the thread exits. Properly designed, you can set an upper limit to the time this will take.

paxdiablo
+1  A: 

Use a synchronisation object such as an Event. For example, each background thread has an Event associated with it. When the thread is terminating, it signals the Event. The main thread does a WaitHandle.WaitAll on the set of Events, and proceeds only when all Events are signalled.

Be warned that if there is a chance that the background threads will take a long time to terminate, blocking the main thread while waiting for them would create a bad user experience. So if this is the case, you may want to hide the window before blocking. Also, you'll want to test what the impact of this is on your callback delegate -- if the UI thread is blocked in a wait, will it be able to handle your delegate?

Might not a better design be not to call the delegate if the thread is being killed due to the window closing? Just have the main thread tell the background threads why they are terminating and have them skip the callback if the reason is "window closing." (This assumes that you are communicating with the threads, as Pax rightly recommends, rather than just calling Abort.)

itowlson