I have a .Net core app that basically does something like this:
public async Task<IOBoundStuffResult> DoIOBoundStuff()
{
// Do IO bound stuff ...
return new IOBoundStuffResult
{
Id = getIdForThing()
};
}
public async Task<OtherIOBoundStuffResult> DoOtherIOBoundStuff()
{
// Do other IO bound stuff ...
return new OtherIOBoundStuffResult
{
Uri = getUriForThing()
};
}
public async Task<IOBoundTaskResult> DoIOBoundStuff()
{
var ioBoundTask1 = doIOBoundStuff();
var ioBoundTask2 = doOtherIOBoundStuff();
return await Task.WhenAll(ioBoundTask1, ioBoundTask2)
.ContinueWith((task) =>
{
var id = ioBoundTask1.Result.Id;
var uri = ioBoundTask2.Result.Uri;
doSomethingWithIdAndUri(id, uri);
return new IOBoundTaskResult
{
Id = id,
Uri = uri
};
});
}
public async Task<IActionResult> DoThing()
{
try
{
var cpuBoundTask = Task.Run(() =>
{
doCPUBoundStuff();
});
var ioBoundTask = DoIOBoundStuff();
// do stuff with ioBoundTask, cpuBoundTask
}
catch (System.Exception ex)
{
// Process System.Exception.AggregateException, other exceptions
}
}
The problem here is that if something in one of those tasks throws an exception (in particular doSomethingWithIdAndUri()) then the exception is not caught by the try...catch block and results in a crash. I've tried creating continuation tasks with TaskContinuationOptions.OnlyOnFaulted to handle exceptions, but all that seems to do is always cause a TaskCancelledException to be thrown. How can I catch exceptions that are thrown from tasks?