在.NET 4.5仍然崩溃的应用程序不可观测任务异常 [英] Unobserved Task exceptions in .NET 4.5 still crash app
问题描述
为了让开发者更容易编写异步code根据 任务,.NET 4.5更改为未观测到的默认异常行为 异常。虽然没有观察到异常仍然会导致 UnobservedTaskException事件得到提升(不这样做将是一个 重大更改),这个过程不会在默认情况下崩溃。相反,本 异常将最终得到吃掉引发该事件后, 不管事件处理程序是否遵守例外。
To make it easier for developers to write asynchronous code based on Tasks, .NET 4.5 changes the default exception behavior for unobserved exceptions. While unobserved exceptions will still cause the UnobservedTaskException event to be raised (not doing so would be a breaking change), the process will not crash by default. Rather, the exception will end up getting eaten after the event is raised, regardless of whether an event handler observes the exception.
但我的实验结果,上述说法不匹配。下面是我的code:
But the result of my experiment does not match the above statement. Below is my code:
static void Main(string[] args)
{
DownloadAsync("http://an.invalid.url.com);
}
async static void DownloadAsync(string url)
{
using (var client = new System.Net.Http.HttpClient())
{
string text = await client.GetStringAsync(url);
Console.WriteLine("Downloaded {0} chars", text.Length);
}
}
由于我传递一个无效的网址 DownloadAsync()
方法,调用的HttpClient
的 GetStringAsync()
方法将引发expcetion,它的应用程序崩溃。
Since I pass an invalid url to DownloadAsync()
method, the call to HttpClient
's GetStringAsync()
method will throw an expcetion, and it crashes the application.
所以我的问题是:在默认情况下在.NET 4.5仍然崩溃的应用程序没有观察到异常
So my question is: Does unobserved exceptions in .NET 4.5 still crash app by default?
推荐答案
您确实有一个工作
有一个例外(由 GetStringAsync返回的
)。但是,等待
被观测工作
例外,然后传播出去的 DownloadAsync
办法(即异步无效
)。
You do have a Task
with an exception (the one returned by GetStringAsync
). However, the await
is observing the Task
exception, which then propagates out of the DownloadAsync
method (which is async void
).
异常繁殖出异步无效
方法不同的表现;他们提出的的SynchronizationContext
这是积极的,当异步无效
方法启动(在这种情况下,一个线程池的SynchronizationContext
)。这是的没有的视为未观测到的异常。
Exceptions propagating out of async void
methods behave differently; they are raised on the SynchronizationContext
that was active when the async void
method started (in this case, a thread pool SynchronizationContext
). This is not considered an unobserved exception.
如果您更改 DownloadAsync
返回工作
,那么你将有一个实际的不可观测的任务
例外,这将被忽略(正确):
If you change DownloadAsync
to return Task
, then you will have an actual unobserved Task
exception, which will be ignored (correctly):
static void Main(string[] args)
{
DownloadAsync("http://an.invalid.url.com);
Console.ReadKey();
}
async static Task DownloadAsync(string url)
{
using (var client = new System.Net.Http.HttpClient())
{
string text = await client.GetStringAsync(url);
Console.WriteLine("Downloaded {0} chars", text.Length);
}
}
这篇关于在.NET 4.5仍然崩溃的应用程序不可观测任务异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!