所以我读了async / await和某个地方的某个地方,我读到的是,如果您不等待异步方法,则基本上会丢失它。它会触发并忘记并进入AEeher,如果引发异常-您将永远不会知道。 这是作者使用的示例:
static async void OnButtonClick()
{
yolo();
string imageUrl = null;
try
{
DownloadAndBlur(imageUrl);
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
Console.WriteLine("Done!");
}
static async Task DownloadAndBlur(string url)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
}
Indeed, if I call the OnButtonClick()
method from my code no exception gets thrown, or rather, nothing about an exception is printed on the console. While if I await the DownloadAndBlur
method - an exception is written to the console.
因此,我尝试复制该行为并将其编写为:
static async void Execute()
{
Console.WriteLine(1);
yolo();
Console.WriteLine(2);
}
static Task yolo()
{
throw new Exception();
}
但是会引发异常,而我的调试会话将其捕获。那么有什么不同,因为我认为它们是相同的。
Maxim 26.只要您从未忘记过,“ Fire and Forget”就可以了。
在多任务处理中获得异常总是很困难的。
如果您正在执行Mutlthreading,默认情况下实际上很容易松散所有异常。线程本身吞没了所有异常。这是必须处理的最坏情况。
As a result, Multitasking approaches always catch all exceptions, then expose them in the Result. Task has a property for that. So Does RunWorkerCompletedEventArgs.
延续代码的一项工作是检查并重新引发任何异常。 Task必须为多线程支持做些事情,即使仅使用多任务并没有必要。