Exceptions are not received in caller when using ASYNC

后端 未结 1 1724
有刺的猬
有刺的猬 2021-01-24 09:56

I am using DispatcherTimer to process a method at a specified interval of time

dispatcherTimer = new DispatcherTimer()
{
   Interval = new TimeSpan(         


        
1条回答
  •  离开以前
    2021-01-24 10:25

    This is the downside of using async void. Change your method to return async Task instead :

    private async static Task MethodWithParameter(string message)
    {
        try
        {
            await MQTTPublisher.RunAsync(message);
    
        }
        catch (Exception Ex)    
        {
    
        }            
    }
    

    Based on: 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.

    And:

    Figure 2 Exceptions from an Async Void Method Can’t Be Caught with Catch

    private async void ThrowExceptionAsync()
    {
        throw new InvalidOperationException();
    }
    
    public void AsyncVoidExceptions_CannotBeCaughtByCatch()
    {
        try
        {
            ThrowExceptionAsync();
        }
        catch (Exception)
        {
            // The exception is never caught here!
            throw;
        }
    }
    

    0 讨论(0)
提交回复
热议问题