When using discard (_) to an async task the try catch does not catch the inner exception of the called method

928 Views Asked by At

I work on a .net framework project MVC and currently I am facing the following issue.

I have an api

[HttpGet]
[ActionName("testme")]
public async Task<bool> TestMe()
{
  await AddNoteAsync("Test");
  return true;
}

And the AddNoteAsync is:

public static async Task AddNoteAsync(string note)
{
  try
  {  var client = new Client()              
    await client.Note.CreateAsync(note);    
  }
  catch (Exception)
  {               
   // ignored
  }
}

This works fine when there is an exception from CreateAsync()

The problem comes when I want discard the AddNoteAsync as following:

[HttpGet]
[ActionName("testme")]
public bool TestMe()
{
  _ = AddNoteAsync("Test");
  return true;
}

This one eventually will return

"System.AggregateException A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread."

even though that I await inside the AddNoteAsync.

How can I modify the code so that I will not get aggregation exception?

1

There are 1 best solutions below

0
Paulo Morgado On

Using this code:

[HttpGet]
[ActionName("testme")]
public bool TestMe()
{
  _ = AddNoteAsync("Test");
  return true;
}

You are invoking a potentially asynchronous method.

If the method has not completed, TestMe will return immediately and the exception won't be caught.

You can see the difference in these 2 versions of AddNoteAsync:

async Task AddNoteAsync1(string s)
{
    throw new Exception("BOOM!");
}
async Task AddNoteAsync2(string s)
{
    await Task.Delay(10000);
    throw new Exception("BOOM!");
}
``