Try Catch outside of: await Task.Run(()

有些话、适合烂在心里 提交于 2019-12-18 04:38:12

问题


Does try catch outside of: await Task.Run(() => make sense or just use them only inside of await?

private async void Test()
{
     try
     {
         await Task.Run(() =>
         {
             try
             {
                  DoingSomething();
             }
             catch (Exception ex)
             {
                  log.Error(ex.Message);
             }
         });
      }
      catch (Exception ex)
      {
          log.Error(ex.Message);
      }
}

回答1:


If you handle Exception inside the delegate (in your case just for logging purpose), await will not raise an exception in normal circumstances. This should be fine.

private async Task Test()
{
         await Task.Run(() =>
         {
             try
             {
                  DoingSomething();
             }
             catch (Exception ex)
             {
                  log.Error(ex.Message);
             }
         });

}

However, since you are awaiting the Task, most probably, there will be some DoSomethingElse in the Test method, which might be affected by the outcome of the Task - in which case it also makes sense to have a try/catch around await.

private async Task Test()
{
     try
     {
         await Task.Run(() =>
         {
             try
             {
                  DoingSomething();
             }
             catch (SomeSpecialException spex)
             {
                  // it is OK to have this exception
                  log.Error(ex.Message);
             }
         });

         DoSomethingElse(); // does not run when unexpected exception occurs.
      }
      catch (Exception ex)
      {
          // Here we are also running on captured SynchronizationContext
          // So, can update UI to show error ....
      }
}



回答2:


If the delegate you pass to Task.Run raises an exception, then you can catch it outside the Task.Run when you await the returned task.

You shouldn't think of await as though it was a block. There's no such thing as "inside of await". Instead, think of await as an operator that takes a single argument (in this case, the Task returned by Task.Run). Task.Run will catch exceptions from its delegate and place them on the returned Task; await will then propagate that exception.




回答3:


You can add try catch to outside code too. The compiler will execute catch section when an exception happens during the async call. Here is more details why would you need try catch around await http://msdn.microsoft.com/en-us/library/vstudio/0yd65esw.aspx look Exceptions in Async Methods



来源:https://stackoverflow.com/questions/17704102/try-catch-outside-of-await-task-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!