Tutorial :C#: Stopping a thread after an Exception



Question:

I have this code:

Thread t = new Thread(() => UpdateImage(origin));  t.Name = "UpdateImageThread";  t.Start();  

If method UpdateImage(origin) throw an exception, it is necessary to stop thread or it will be stoped after the exception?

Thank you!


Solution:1

If UpdateImage throws an exception, it is probably going to take down your whole process. Any thread that raises a top-level exception indicates a big problem. You should wrap this, for example by putting try/catch around UpdateImage and doing something suitable. And yes, if an exception gets to the top of a thread, the thread is dead:

Thread t = new Thread(() => {      try {UpdateImage(origin); }      catch (Exception ex) {Trace.WriteLine(ex);}  });  t.Name = "UpdateImageThread";  t.Start();  

(or your choice of error handling)


Solution:2

Since .NET 2.0, when a background thread throws an exception (that is not handled), the .NET runtime will take down your process. In a Windows.Forms application, this is different; you can use the Application.ThreadException event to catch the exception.

This was different in .NET 1.0/1.1, you can read about the whole topic here (e.g. how to enable the legacy behavior with .NET 2.0 or later): http://msdn.microsoft.com/en-us/library/ms228965.aspx#ChangeFromPreviousVersions.

No matter whether you use Windows.Forms or the legacy behavior - if the process does not exit, you do not need to explicitly stop the thread; the exception will stop it.


Solution:3

The exception will not cause the thread to stop if it is caught somewhere in the UpdateImage method - unless the catch clause explicitly returns from the method.

If it is unhandeled, your application will crash anyway - thus causing the Thread to stop ;)

It is best to place a try...catch block in your UpdateImage method and perform your logic error handling there where it belongs. You can then decide for yourself weather to return and end the thread or try again


Solution:4

it is like the main thread, for example if there is exception occured in the main thread and you no one catch it, so the main thread'll terminate and your application.

The same thing for user threads


Solution:5

The thread will terminate automatically as you are not handling the exception, along with the rest of your process, assuming you are on .Net 2.0 or greater (which I assume you are due to the C# 3 syntax in the question).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »