如何使线程不崩溃的应用程序

use*_*956 0 c# multithreading

我们假设我有以下控制台应用程序:

Thread thread = new Thread(new ThreadStart(() => { throw new Exception(); }));
thread.IsBackground = true;
thread.Start();

while (true)
  Console.WriteLine("Hello from main thread");
Run Code Online (Sandbox Code Playgroud)

是否有可能使整个应用程序不会崩溃,因为后台踏板的异常(当然不使用try..catch)?

Ale*_*nik 5

附加未处理的异常处理程序:http: //msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

使用全局处理程序可以更好地实现所需结果(使用try/catch,但只能使用一次):

    public static void GlobalHandler(ThreadStart threadStartTarget)
    {
        try
        {
            threadStartTarget.Invoke();
        }
        catch (Exception ex)
        {
             //handle exception here
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后开始你的线程:

        Thread thread = new Thread(o => GlobalHandler(ThreadMethod));
        thread.Start();
Run Code Online (Sandbox Code Playgroud)

PS但是,实际上,我不喜欢捕获所有异常的想法.这几乎从来都不是好主意.