Hi I have the following code:
try
{
var t1 = Task.Factory.StartNew(() =>
{
Count(5, 10);
});
//t1.Wait(); //This line if uncommented causes the exception to be handled below....
Console.WriteLine("done");
}
catch (AggregateException ex)
{
Console.WriteLine(ex);
}
private void Count(int start, int end)
{
for (var i = start; i <= end; i++)
{
Console.WriteLine(i);
if (i == 7) throw new InvalidOperationException("Something bad happened");
Thread.Sleep(1000);
}
}
If I dont want to wait on my task, but still want to handle exceptions, how can I achieve this?
Create a continuation that handles errors when the task fails:
OnlyOnFaultedspecifies that the continuation will run on a threadpool thread if the task fails. If the task completes successfully, then it won’t execute.