问题描述
我完全迷惑不解我确信,如果在线程中没有捕获到异常,那么.NET会关闭整个应用程序域,我从来没有测试过这个异常。然而,我刚刚尝试了以下代码,并没有失败...有没有人可以解释为什么?
(在.NET 4和3.5中尝试)
static void Main(string [] args)
{
Console.WriteLine(Main thread {0},Thread.CurrentThread.ManagedThreadId);
Action a = new Action(()=>
{
Console.WriteLine(Background thread {0},Thread.CurrentThread.ManagedThreadId);
抛出新的ApplicationException(test exception);
});
a.BeginInvoke(null,null);
Console.ReadLine();
}
code> BeginInvoke 内部使用 ThreadPool
当 ThreadPool
时,任何未经混淆的异常将沉默失败但是,如果您使用 a.EndInvoke
,那么未分配的异常将抛出 EndInvoke
方法。
JoãoAngelo
表示使用 ThreadPool
方法直接喜欢 ThreadPool.QueueUserWorkItems
和 UnsafeQueueUserWorkItem
将抛出2.0及更高版本的异常。 I am completely puzzled. I was so sure that .NET shuts the whole application domain if there is uncaught exception in a thread that I never tested this.
However I just tried the following code and it doesn't fail... Could anyone please explain why?
(Tried in .NET 4 and 3.5)
static void Main(string[] args)
{
Console.WriteLine("Main thread {0}", Thread.CurrentThread.ManagedThreadId);
Action a = new Action(() =>
{
Console.WriteLine("Background thread {0}", Thread.CurrentThread.ManagedThreadId);
throw new ApplicationException("test exception");
});
a.BeginInvoke(null, null);
Console.ReadLine();
}
This is happening because the BeginInvoke
uses ThreadPool
internally and when ThreadPool
any unhadled exceptions will be silence fail. However if you use a.EndInvoke
then the unhadled exception will be throw at the EndInvoke
method.
Note: as João Angelo
stated that using ThreadPool
methods directly "like ThreadPool.QueueUserWorkItems
and UnsafeQueueUserWorkItem
" will throw exceptions at 2.0 and above.
这篇关于为什么未处理的异常在后台线程不会崩溃应用程序域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!