Loading

《C#并发编程经典实例》学习笔记—2.9 处理 async void 方法的异常

问题

需要处理从 async void 方法传递出来的异常。

解决方案

书中建议尽量不写 async void 这样的方法,如果非写不可,建议在方法内部 try catch 所有的代码,即在方法内部处理好所有可能的异常。

当然处理 async void 方法的异常,还有一个办法,即全局异常处理方法中进行异常处理,当然这个办法算不是办法的办法。全局异常处理可以处理 async void 方法的异常,是因为当异常从 async void 方法抛出的时候,可以在 SynchronizationContext Class (System.Threading) | Microsoft Docs 引发出来。前提是当前平台支持SynchronizationContext。

SynchronizationContext 适用于

.NET Core
3.0 2.2 2.1 2.0 1.1 1.0
.NET Framework
4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0
.NET Standard
2.1 2.0 1.6 1.4 1.3 1.2 1.1 1.0
UWP
10.0
Xamarin.Android
7.1
Xamarin.iOS
10.8
Xamarin.Mac
3.0

全局处理异常机制:WPF 有 Application.DispatcherUnhandledException ,WinRT有 Application.UnhandledException ,ASP.NET 有 Application_Error ,Asp.NET Core可以添加异常过滤器,自己实现的全局异常过滤器需继承接口 IExceptionFilter ,或者添加异常处理中间件。

在不支持的平台需要自己操作SynchronizationContext进行 async void 的异常处理,可以借助已有的处理方案,即免费的 NuGet 库 Nito.AsyncEx 。

作者给出的示例代码,借助AsyncContext对异常进行处理。AsyncContext封装了对SynchronizationContext的操作,源码参考 AsyncEx/AsyncContext.TaskScheduler.cs at master · StephenCleary/AsyncEx

static class Program
{
    static int Main(string[] args)
    {
        try
        {
            return AsyncContext.Run(() => MainAsync(args));
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex);
            return -1;
        }
    }
    static async void MainAsync(string[] args)
    {
        //...
    }
}
posted @ 2019-10-23 11:32  repeatedly  阅读(450)  评论(0编辑  收藏  举报