.NET Async Utility

08 October 2012

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.

 1 using System.IO;
 2 using System.Threading;
 3 public static class AsyncUtil
 4 {
 5     private static readonly log4net.ILog _log =
 6         log4net.LogManager.GetLogger(typeof(AsyncUtil));
 7     
 8     /// <summary>
 9     /// This is a fire-and-forget type execution...
10     /// </summary>
11     /// <param name="action">
12     /// The action method that you want to run asynchronously.
13     /// </param>
14     /// <param name="onError">
15     /// The action method that you want to run after an exception.
16     /// </param>
17     public static void AsyncExecute(Action action,
18         Action<ErrorEventArgs> onError)
19     {
20         ThreadPool.QueueUserWorkItem(item =>
21         {
22             try
23             {
24                 action();
25             }
26             catch(Exception ex)
27             {
28                 _log.Error(ex);
29                 if(onError!=null)
30                 {
31                     var args = new ErrorEventArgs(ex);
32                     onError(args);
33                 }
34             }
35         });
36     }
37 }