Monday, October 8, 2012

.NET Async Utility

Below is a simple C# class that I've used on many projects over the years for fire-and-forget type operations. For example, if you have a data collection service that pools multiple sources for information, you probably do not want to wait for the first remote call to finish before moving on to the next. This utility can be used to simply move that operation on to another thread to be executed.

The one caveat to keep in mind is that, in cases of exceptions, the onError action gets executed on a different thread than the original caller. This means that you need to be careful to synchronize your threads before changing GUI controls.


using System.IO;
using System.Threading;
public static class AsyncUtil
{
 private static readonly log4net.ILog _log = 
  log4net.LogManager.GetLogger(typeof(AsyncUtil));
 
 /// <summary>
 /// This is a fire-and-forget type execution...
 /// </summary>
 /// <param name="action">
 /// The action method that you want to run asynchronously.
 /// </param>
 /// <param name="onError">
 /// The action method that you want to run after an exception.
 /// </param>
 public static void AsyncExecute(Action action, 
  Action<ErrorEventArgs> onError)
 {
  ThreadPool.QueueUserWorkItem(item =>
   {
   try
   {
    action();
   }
   catch(Exception ex)
   {
    _log.Error(ex);
    if(onError!=null)
    {
     var args = new ErrorEventArgs(ex);
     onError(args);
    }
   }
   });
 }
}

No comments:

Post a Comment