Thursday, February 13, 2014

Async task helper


Here is a simple helper class for async tasks. The helper class encapsulates code for creating task, This is a very interesting way to isolate the complexity of task programming. Class implementation is nothing much fancy, Async and await keywords are only used in the helper class so our main code remains very clean. The method DoAsync accepts three parameters, one function and two action. First is the function that is the actual work or task we want to accomplish asynchronously, second action is fired when the work is completed successfully and the third parameter is a action that is fired in case of an exception.

   1: using System;
   2: using System.Threading.Tasks;
   3:  
   4: namespace Common.Helper
   5: {
   6:     public class TaskHelper
   7:     {
   8:         public static void DoAsync<T>(Func<T> work, Action<T> completed, Action<Exception> exceptionHandler)
   9:         {
  10:             Task<T> task = AsyncTask(work);
  11:             task.GetAwaiter().OnCompleted(() =>
  12:             {
  13:                 if (task.IsFaulted)
  14:                     exceptionHandler(task.Exception);
  15:                 else
  16:                     completed.Invoke(task.Result);
  17:             });
  18:         }
  19:  
  20:         private static async Task<T> AsyncTask<T>(Func<T> func)
  21:         {
  22:             return await Task.Run(func);
  23:         } 
  24:     }
  25: }

 

Below is a very simple class that utilize TaskHelper. Assuming that we are using the class in a UI application to perform some lengthy work, once the work is complete we want to display some data to the user. The method DoWork is suppose to perform the lengthy work and return the result as a string value. Once the work is finish the method WorkCompleted will be invoked, if there are any exception during this process the method HandleException should handle and display proper error to the user.

 


   1: public class SomeTask
   2: {
   3:     public SomeTask()
   4:     {
   5:         TaskHelper.DoAsync<string>(DoWork, WorkCompleted, HandleException); 
   6:     }
   7:     private string DoWork()
   8:     {
   9:         return "TaskDone";
  10:     }
  11:     private void WorkCompleted(string status)
  12:     {
  13:     }
  14:     private void HandleException(Exception ex)
  15:     {               
  16:     }
  17: }

No comments:

Post a Comment