为什么这个线程代码不会终止?

时间:2014-07-10 08:44:56

标签: c# multithreading exception

我在C#.Net 4.5下试验线程和异常,并且我以某种方式创建了一个无限循环而不使用for,while,do-while或递归。如果我在Visual Studio中执行/调试此代码,则VS会在每个异常处停止(我一直按“继续”)。

static void Main(string[] args)
{
    AppDomain.CurrentDomain.UnhandledException += unhandledException;
    new Thread(new ThreadStart(() => { throw new Exception("Thread.Start (ThreadID: " + Thread.CurrentThread.ManagedThreadId + ")"); })).Start();
    ThreadPool.QueueUserWorkItem(new WaitCallback(_ => { throw new Exception("ThreadPool.QueueUserWorkItem (ThreadId: " + Thread.CurrentThread.ManagedThreadId + ")"); }));
    Task.Run(() => { throw new Exception("Task.Run (" + Thread.CurrentThread.ManagedThreadId + ")"); });

    if (Debugger.IsAttached) Console.ReadLine();
}

private static void unhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Console.WriteLine("Unhandeled {0}:\t{1}", e.ExceptionObject.GetType().Name, (e.ExceptionObject as Exception).Message);
}

当我在没有VS的情况下运行此应用程序时,Windows会终止该程序,因为它没有响应 那么,这里发生了什么?为什么这些例外不会只出现一次?

2 个答案:

答案 0 :(得分:0)

Debug上的Thrown设置 - >可能会选择“公共语言运行时例外”类别下的“例外”对话框(Ctrl + Alt + E)。尝试将其关闭

enter image description here

答案 1 :(得分:0)

问题是你每次创建一个新线程时都会抛出一个新的异常,导致下一个线程调用一个新的异常,它在下一个线程上调用一个新的异常,依此类推。

根据我的理解,您希望在新线程中抛出自己类型的新异常并处理它。

我们需要做的是将我们的委托绑定到waitcallback方法,而不是将新的异常绑定到它。

AppDomain.CurrentDomain.UnhandledException += unhandledException;
ThreadPool.QueueUserWorkItem(new WaitCallback(_ => unhandledException("something", new UnhandledExceptionEventArgs("exception", true) )));
//we bind the unhandledException delegate to it instead of a throwing new exception
new Thread(new ThreadStart(() => { new Exception("Thread.Start (ThreadID: " + Thread.CurrentThread.ManagedThreadId + ")"); })).Start();
Task.Run(() => { throw new Exception("Task.Run (" + Thread.CurrentThread.ManagedThreadId + ")"); });
if (Debugger.IsAttached) Console.ReadLine();