views:

673

answers:

3

I would like an elegant way to capture a thread end/exit event. I've found two approaches so far:

  1. Use background worker, which has a RunWorkerCompleted event, or,
  2. Have my thread worker explicitly call an "I'm Exiting" delegate.

Yes, these will work, but there must be some way from the parent thread (the thread that calls the Thread.Start() method) to detect when a thread has exited regardless of why, how or when. For example, the Visual Studio Debug Output window reports when threads exit :, "The thread 0x1454 has exited with code 0 (0x0)." So it must be possible.

Thanks in advance for any ideas!

+1  A: 

you can poll the ThreadState or IsAlive Properties from the Parent Thread

Baget
The problem with doing this is that ThreadState will show WaitSleepJoin if it is waiting for a particular instruction to execute. So, a thread in WaitSleepJoin may look like a dead thread when it's actually not. This, among a host of other reasons (including the disclaimer in the middle of the page you reference), make it undesirable for getting the actual state of a child thread.
AJ
+3  A: 

If you have a reference to Windows Forms, there's the Application.ThreadExit event.

Personally, I typically wrap my thread handling into my own classes (for many reasons, mostly dealing with making it much cleaner to create and start a thread with many arguments) - which makes having a Complete event trivial to add. Just have the thread's run code call your thread work delegate, then raise the complete event.

Reed Copsey
A: 

you could use thread.join() this is a blocking command, but will continue to perform com and sendMessage.

Thread t = new Thread (delegate() { Console.ReadLine(); });

t.Start();

t.Join();    // Wait until thread t finishes

Console.WriteLine ("Thread t's ReadLine complete!");
AndrewB