系统反射 .Invoke() 无法在调用的异步方法中捕获异常

System reflection .Invoke() cant catch expections inside invoked method which is async

我未能成功调用 async void 方法并从该方法中捕获异常。没有异步的 voids 工作得很好。我真的希望有一个解决方案。下面是一些示例:

class Test
{
    public static void InvokeMethod()
    {
        try
        {
            typeof(testmethods).GetMethod("TestMethod").Invoke(null, null);
            typeof(testmethods).GetMethod("TestAsyncMethod").Invoke(null, null); 
            //This one throws an exception but doesent catch it.
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.InnerException);
        }
    }
}

public class testmethods
{
    public static void TestMethod()
    {
        throw new Exception("Test");
    }

    public static async void TestAsyncMethod()
    {
        throw new Exception("TestAsync");
    }
}

另外大家有什么好的替代品也欢迎大家推荐

文章 Async/Await - Best Practices in Asynchronous Programming 很好地解释了您的场景以及无法捕获异常的原因。

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.

简而言之:考虑将 async void 更改为 async TaskAsync void 仅推荐用于事件处理程序。