How to avoid nested AggregateException when using Task.ContinueWith?
C#5 async/await will help you deal with continuations and proper exception handling while simplifying the code.
public async Task<T> GetResultAsync()
{
var result = await PerformOperationAsync().ConfigureAwait(false);
return DoSomethingWithResult(result);
}
Your method is already marked as async, is it intended ?
To keep the continuation you can provide a TaskContinuationOptions
with OnlyOnRanToCompletion
value :
PerformOperationAsync().ContinueWith(x =>
{
var result = x.Result;
return DoSomethingWithResult(result);
}, TaskContinuationOptions.OnlyOnRanToCompletion);
or use the awaiter to raise the original exception
PerformOperationAsync().ContinueWith(x =>
{
var result = x.GetAwaiter().GetResult();
return DoSomethingWithResult(result);
}, cancellationToken);