How to handle Task.Run Exception

后端 未结 7 1058
离开以前
离开以前 2020-12-08 06:12

I had a problem with catching the exception from Task.Run which was resolved by changing the code as follows. I\'d like to know the difference between handling

7条回答
  •  感情败类
    2020-12-08 07:00

    You can just wait, and then exceptions bubble up to the current synchronization context (see answer by Matthew Watson). Or, as Menno Jongerius mentions, you can ContinueWith to keep the code asynchronous. Note that you can do so only if an exception is thrown by using the OnlyOnFaulted continuation option:

    Task.Run(()=> {
        //.... some work....
    })
    // We could wait now, so we any exceptions are thrown, but that 
    // would make the code synchronous. Instead, we continue only if 
    // the task fails.
    .ContinueWith(t => {
        // This is always true since we ContinueWith OnlyOnFaulted,
        // But we add the condition anyway so resharper doesn't bark.
        if (t.Exception != null)  throw t.Exception;
    }, default
         , TaskContinuationOptions.OnlyOnFaulted
         , TaskScheduler.FromCurrentSynchronizationContext());
    

提交回复
热议问题