July 5, 2011

WaitHandles’ Switch

Filed under: .net,multi-threading Himanshu @ 3:57 pm

I will say it again: “I like extension methods”. They provide great way of increase readability of the code in languages like C#.

Anyway this post is not about extension method. Have you ever needed to write code that will wait on different wait handles (WaitHandle) and execute different piece of code depending up on which handle is signaled. Here is one way to implement that:

public static void WaitSwitch(this WaitHandle[] waitHandles, params Action[] actions)
  
{
  
    waitHandles.DoEmptyOrNullArgCheck("waitHandles");
  
    actions.DoEmptyOrNullArgCheck("waitHandles");
  
    if (waitHandles.Length != actions.Length)
  
        throw new ArgumentException("length of wait handles and actions has to be same");
  
    var triggerIndex = WaitHandle.WaitAny(waitHandles);
  
    actions[triggerIndex]();
  
}
  

And then client code will become as:

(new[] { shutdownTriggeredEvent, updateAvailableEvent }).WaitSwitch(
  
    () => isShutdownRequested = true,
  
    DownloadNextUpdate
  
);
  

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress