简体   繁体   中英

C#: Stopping a thread after an Exception

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!

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)

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 (eg 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.

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

假设您使用.Net 2.0或更高版本(我假设您是由于问题中的C#3语法),线程将在您不处理异常时自动终止,以及您的其余进程。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM