Category Archives: C#

Posts with tips or insights using the C# language.

Lock Access to Multiple Resources with C# Mutex and WaitHandle.WaitAny

I came across a problem while developing a WCF service. I needed to increase the load handling capability, however the number of connections were limited and each needed to call an external service synchronously. I needed a mutex but I needed more than one at a time.

The lock statement wasn’t going to do the job because that will only allow one thread at a time into the critical section. What I needed was a mutex that would allow exactly 8 thread at one time.

Luckily there is a way to solve this problem with .NET libraries. The course of action is to create an array of Mutex objects and an array of your Manager objects. Using the method WaitHandle.WaitAny, you can wait for one of them to become available. At that point use the manager object with the same index.

The WaitAny call will block the thread until one of the resources becomes available. It returns the index of the lock that was taken, or a special value if a timeout occurred.

Here’s the code:

class Program
{
    private const int MANAGER_TIMEOUT = 5000;
    private const int MANAGER_COUNT = 6;
    private static Mutex[] ManagerLocks;
    private static ManagerOfSomeSort[] Managers;
 
    static Program()
    {
        ManagerLocks = new Mutex[MANAGER_COUNT];
        Managers = new ManagerOfSomeSort[MANAGER_COUNT];
        for (int i = 0; i < MANAGER_COUNT; i++)
        {
            ManagerLocks[i] = new Mutex();
            Managers[i] = new ManagerOfSomeSort();
        }
    }
 
    public void HandleRequest()
    {
        var index = WaitHandle.WaitAny(ManagerLocks, MANAGER_TIMEOUT);
        if (index == WaitHandle.WaitTimeout)
            return;  // log an timeout error perhaps
        try
        {
            var manager = Managers[index];
            manager.DoSomething();
        }
        finally
        {
            ManagerLocks[index].ReleaseMutex();
        }
    }
}

How to tell if a path is relative or absolute

There is no function or method in the .NET framework to find this out directly.  I had though that Path.IsPathRooted(string) would do the job, but it seems that paths can be both relative, and rooted.  The path "C:bin\Debug\app.exe" is perfectly valid.  So, the only thing to do is to take the input, create the absolute path, and compare them.  Like this:

private void CheckDestination(string destination)
{
   // Ensure that path is absolute.  Ignore case
   // because filesystem is case-insensitive
   if (string.Compare(destination.Trim(),
      Path.GetFullPath(destination), true) != 0)
   {
        // path is absolute
   }
}