C#: Остановка потока после Исключения

Вот пример от Python IAQ Peter Norvig, Как я делаю Шаблон "одиночка" в Python? (Необходимо использовать функцию поиска браузера для нахождения этого вопроса, нет никакой прямой ссылки, извините)

, Также у Bruce Eckel есть другой пример в его книге , Думающей в Python (снова нет никакой прямой ссылки на код)

9
задан VansFannel 15 July 2009 в 08:22
поделиться

5 ответов

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)

16
ответ дан 4 December 2019 в 07:14
поделиться

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.

10
ответ дан 4 December 2019 в 07:14
поделиться

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

3
ответ дан 4 December 2019 в 07:14
поделиться

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

1
ответ дан 4 December 2019 в 07:14
поделиться

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).

1
ответ дан 4 December 2019 в 07:14
поделиться
Другие вопросы по тегам:

Похожие вопросы: