Wednesday, 16 December 2015

C# Handle Exceptions on TASK

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.


 // Run Stuff in BackGround
 Task.Factory.StartNew(() =>;
     //Do this in the background
  }).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} ";


       //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

 }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

No comments:

Post a Comment

Comments are welcome, but are moderated and may take a wee while before shown.