Tasks are great, run stuff in the background and let the UI without any bad freezing or usual problems with calling webservices or intensive tasks.
But Handling exceptions in called Task is easy enough when you know how
The Key is looking at the
Task.IsFaulted bool.
- Task.IsFaulted is true : The task was ended on an exception.
- Task.IsFaulted is false: The task was ended normally (no exception)
Exceptions Returned by Task
The exceptions are returned as a collection, the top exception is fairly useless and you have look at the innerException to find the real cause for the issue.
What if I don't handle Exceptions
Well!! you code will run as the Task was run successfully and your calling layer/ui may be in a state that is less than ideal and your application may stop working and it may (read will) take a long time for you to find out or debug the exact issue. Tasks without exception handling are black holes waiting to happen.
CODE
// Run Stuff in BackGround
Task.Factory.StartNew(() =>;
{
//Do this in the background
SomeIntensiveJob();
}).ContinueWith(task =>;
{
//Check to see if there was a exception on the task handle it.
if (task.IsFaulted)
{
string exMessage = "unknown error";
string exStack = "unknow Exception is null";
if (task.Exception != null)
{
//Log all the Exceptions (maybe lots)
foreach (var ex in task.Exception.InnerExceptions)
{
exMessage = ex.Message;
exStack = ex.StackTrace;
string errlog = $"Stuff , Exception : {exMessage} , Stack : {exStack} ";
og(errlog);
}
}
//Update Your UI here with Errors
Label.Text = $"Error on stuff {exMessage}, with stack {exStack}";
return; // exit on error
} ////////////////////////// end exception handling ///////////////////////////////////
// do this on the UI thread once the task has finished..
// The task has completed without any issues so do your stuff
runPostTaksStuff();
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());