[英]Console application not torn down by an unhandled task exception
I'm trying to figure out why my console app is not torn down by an unhandled task exception. 我试图弄清楚为什么我的控制台应用程序没有被未处理的任务异常拆除。 All I do is create a task where I immediately throw an exception.
我所做的只是创建一个任务,我立即抛出异常。 Finally I force GC.
最后我强迫GC。 In the first example I have a handler for the
TaskScheduler.UnobservedTaskException
event and I can see the exception get handled. 在第一个例子中,我有一个
TaskScheduler.UnobservedTaskException
事件的处理程序,我可以看到异常得到处理。
static async Task ThrowsException()
{
Console.WriteLine("Throwing!");
throw new Exception("Test exception");
}
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
ThrowsException();
Console.WriteLine("Collecting garbage.");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Done collecting garbage.");
Console.ReadKey();
}
static void TaskScheduler_UnobservedTaskException(object sender,
UnobservedTaskExceptionEventArgs e)
{
Console.WriteLine("Unobserved task exception occured in finalizer.");
Console.WriteLine(e.Exception.InnerException.Message);
}
Output: 输出:
Throwing!
Collecting garbage.
Unobserved task exception occured in finalizer.
Test exception
Done collecting garbage.
But if I comment out the line TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException
the program still runs to completion. 但是,如果我注释掉行
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException
,程序仍然运行完成。 In this case the output is: 在这种情况下,输出是:
Throwing!
Collecting garbage.
Done collecting garbage.
Why doesn't the application crash in this case? 为什么应用程序在这种情况下不会崩溃?
Not crashing the program from a unobserved task exception was a change that was made for .NET 4.5, see the remarks section of the MSDN for the event . 不会从未观察到的任务异常中崩溃程序是对.NET 4.5所做的更改,请参阅MSDN的备注部分以了解该事件 。 If you want your program to have the pre .NET 4.5 behavior and cause it to crash you need to put in your app.config
如果您希望程序具有.NET 4.5之前的行为并导致其崩溃,则需要输入app.config
<configuration>
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>
</configuration>
This will bring back the old behavior. 这将带回旧的行为。
ThrowsException is an async method and therefore unless you'll wait on this method, the exception will be swallowed. ThrowsException是一个异步方法,因此除非您等待此方法,否则将吞下异常。
I assume that you need to call this method like this: 我假设您需要像这样调用此方法:
ThrowsException.Wait();
Or even catch the exception: 甚至可以捕获异常:
try
{
ThrowsException().Wait();
}
catch (AggregateException e)
{
// Do something
}
Also, reading the following will help you understand why it didn't crash your application: TaskScheduler.UnobservedTaskException Event . 此外,阅读以下内容将有助于您了解它为什么不会使您的应用程序崩溃: TaskScheduler.UnobservedTaskException事件 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.