Distributed locking in .NET

hackerhasid picture hackerhasid · Jul 29, 2010 · Viewed 11.5k times · Source

I'm looking for recommendations for a locking mechanism that will work across multiple machines. In my case I basically just want to be able to start a service on 2 machines and have one block until the other finishes as a simple way to insure redundancy in case a service machine goes down.

Sort of along the same lines as Distributed Lock Service but specifically looking for projects that people have successfully integrated with .NET.

Answer

ChaseMedallion picture ChaseMedallion · Mar 15, 2016

We use SqlServer's application lock functionality for distributed locking. This is especially convenient if SqlServer is already a part of your stack.

To make this easier to work with from .NET, I created a NuGet package which makes it easy to use this functionality. The library also supports other backends such as Postgres, Azure blob storage, and Redis.

With this library, the code looks like:

var @lock = new SqlDistributedLock("my_lock_name", connectionString);
using (@lock.Acquire())
{
   // critical region
}

Because the underlying SqlServer functionality is very flexible, there are also overloads supporting TryAcquire semantics, timeouts, and async locking.