A good solution for await in try/catch/finally?

后端 未结 4 1726
南笙
南笙 2020-12-04 07:20

I need to call an async method in a catch block before throwing again the exception (with its stack trace) like this :

try
{
    //         


        
4条回答
  •  感动是毒
    2020-12-04 07:35

    If you need to use async error handlers, I'd recommend something like this:

    Exception exception = null;
    try
    {
      ...
    }
    catch (Exception ex)
    {
      exception = ex;
    }
    
    if (exception != null)
    {
      ...
    }
    

    The problem with synchronously blocking on async code (regardless of what thread it's running on) is that you're synchronously blocking. In most scenarios, it's better to use await.

    Update: Since you need to rethrow, you can use ExceptionDispatchInfo.

提交回复
热议问题