Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
      }
}
like image 253
as74 Avatar asked Jul 17 '13 15:07

as74


People also ask

What happens if you don't await a Task C#?

If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.

Is Task run asynchronous?

In . NET, Task. Run is used to asynchronously execute CPU-bound code.

Does Task run create a new thread?

NET code does not mean there are separate new threads involved. Generally when using Task. Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR.

Does Task wait block?

If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes.


1 Answers

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 ....
      }
}
like image 120
YK1 Avatar answered Sep 21 '22 03:09

YK1