Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distributed locking in .NET

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.

like image 724
hackerhasid Avatar asked Jul 29 '10 17:07

hackerhasid


People also ask

What is locking in distributed systems?

 In Distributed Systems(referred to as DS from now on), lock is a mechanism that allows only one of the innumerable nodes(or process) to access and modify a resource or data that is being shared commonly to prevent execution of same task twice and also maintain data integrity.

When would you use a distributed lock?

Distributed locks provide mutually exclusive access to shared resources in a distributed environment. Distributed locks are used to improve the efficiency of services or implement the absolute mutual exclusion of accesses.

What is the role of distributed lock manager?

A distributed lock manager (DLM) runs in every machine in a cluster, with an identical copy of a cluster-wide lock database. In this way a DLM provides software applications which are distributed across a cluster on multiple machines with a means to synchronize their accesses to shared resources.

What is SQL Distributed Lock?

Sproc. Lock gives a quick and easy way to take and release locks across multiple servers, using SQL Server as a back end.


2 Answers

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.

like image 162
ChaseMedallion Avatar answered Sep 20 '22 05:09

ChaseMedallion


If you are using AppFabric for Windows Server, you can use this DataCache extension. You can also use redis locks with ServiceStack's redis client.

Both are .NET implementations but require a server component. I've been tinkering with a PeerChannel implementation of a distributed lock that uses peer to peer communication and doesn't require any server infrastructure. Let me know if this is something you would be interested in.

like image 34
Guy Godin Avatar answered Sep 21 '22 05:09

Guy Godin