Removing exceptions in a .NET thread

How could you find out that an Exception occurred in Thread in MultiThreaded Application ? and sequentially clean resources?

Because otherwise Thread can remain in memory and work.

+7
multithreading c #
source share
5 answers

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); 
+5
source share

If you are worried about this then you should wrap the stream entry point in a try / catch block and do the cleanup explicitly. Any exception coming out of the stream entry point will disable your application.

+2
source share

but. You have a call stack and you can catch it inside the stream and add the stream identifier to the log, I think ...

If you neatly bind your thread, you can add the cleanup code to the catch section, terminating the thread if necessary.

+1
source share

You can catch exceptions in threads, like any normal function. If your work function for a thread is called DoWork, then do something like this:

 private void DoWork(...args...) { try { // Do my thread work here } catch (Exception ex) { } } 
+1
source share

Eric Lippert recently posted a message about the failure of exceptions that occur in workflows. It is worth reading and understanding that the exception is "exceptional" and the only thing you can be sure is that after the exception in the workflow, you can no longer be sure of the state of your application.

+1
source share

All Articles