C#C
C#3mo ago
RiA

async void

I have a 'void' return type method that needs to launch an async method.

  1. I could use try-catch (I'm used to this approach usually, since the errors can be wrapped up)
    private async void SomeLegacyHandler()
    {
    try { await TargetMethodAsync(); }
    catch(ex) { /*handle logging*/ }
    }
  2. Another suggested answer: Always successful Task (handle exception on the async Task pipeline directly)
    Couldn't the Task method here just be made async anyway? (I mean i know it works without the async, but feels pointless unless deferred awaiting here improves performance in a way i can't see yet)
    private Task SomeLegacyHandlerAsync()
    {
    try { return TargetMethodAsync(); }
    catch(ex) { /*handle logging*/ return Task.CompletedTask; }
    }
    private async void SomeLegacyHandler()
    => await SomeLegacyHandlerAsync();
  3. ContinueWith (this is my main confusion; Does this work? Is this better than #1?)
    private void SomeLegacyHandler()
    {
    _ = await SomeLegacyHandlerAsync()
    .ContinueWith(task => {
    if (task.Exception != null)
      // log here
    }, TaskContinuationOptions.OnlyOnFaulted);
    }
Was this page helpful?