exception disappear when forgot to await an async method
Why exceptions in async methods are “dangerous” in C#
Error handling is a topic that sometimes is neglected when enterprise systems are developed, in C# or any other language, by the fact that there are many tools available in the market that allows us to just easily install and configure, and all the exceptions start being logged automatically. But, what if the wrong exceptions are being recorded? What if our application is hiding important errors and masking the real cause of the issues? It may be an absurd assumption for many developers, but in real-world scenarios, this situation is more common than we sometimes imagine.
To demonstrate what I’m trying to say with this short article, take a look at the code below:
class Program
{
static async Task Main(string[] args)
{
try
{
MyAsyncMethod();
}
catch(Exception ex)
{
Console.WriteLine("Show my exception:");
Console.Write(ex.Message);
}
}
private static async Task MyAsyncMethod()
{
throw new ArgumentException("Exception from MyAsyncMethod");
}
}
No exception was thrown because the MyAsyncMethod routine is not awaited and the exception is literally lost with the Task. In that case, if we are using Application Insights or another logging system, the exception will never be recorded and we will not be able to know that exception occurred. And I’m not even talking about what we should do for handling this error properly in the application. Therefore, the first mistake is not awaiting the task if we want to catch the error in the parent method. If we use the “await” keyword, the exception will be thrown:
This solves the problem for a single simple task, but what if we have multiple tasks running within a method? What’s the result? If we don’t await any of the tasks, the result will be similar to the previous example with a single task: the exception will be lost with the tasks. However, if we await all the tasks, considering multiple exceptions can be thrown, one for each task, the result for the parent method may not be what we are expecting.
还有其他的,关于多任务处理的