As Sean said, you must do exception handling and cleaning inside the thread method, you cannot do this in the thread initialization. For example:
public void Run() { try { Thread thread1 = new Thread(ThreadEntry1); thread1.Start(); Thread thread2 = new Thread(ThreadEntry2); thread2.Start(); } catch (NotImplementedException) { // Neither are caught here Console.WriteLine("Caught you"); } } private void ThreadEntry1() { throw new NotImplementedException("Oops"); } private void ThreadEntry2() { throw new NotImplementedException("Oops2"); }
Instead, this approach is more self-sufficient and obviously also works:
public void Run() { Thread thread1 = new Thread(ThreadEntry1); thread1.Start(); } private void ThreadEntry1() { try { throw new NotImplementedException("Oops"); } catch (NotImplementedException) { Console.WriteLine("Ha! Caught you"); } }
If you want to find out if Thread has failed, you should consider the WaitHandles array and return the signal to your calling method. An alternative and simpler approach is to simply increase the counter each time a thread operation ends:
Interlocked.Increment(ref _mycounter);
Chris s
source share