Tero
Tero

Reputation: 140

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

I have not been successful in invoking an async void method and catching exceptions from that method. voids without async work just fine. I really wish for a solution. Heres some examples:

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");
    }
}

Also if you have some good alternatives, please feel free to recommend

Upvotes: 2

Views: 171

Answers (1)

Ralf Bönning
Ralf Bönning

Reputation: 15415

The article Async/Await - Best Practices in Asynchronous Programming gives a good explanation of your scenario and why the exception cannot be catched.

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.

In short: Think about changing async void to async Task. Async void is only recommended for event handlers.

Upvotes: 2

Related Questions