Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

DistributedLock

> 编程语言
Open source

A .NET library for distributed synchronization

2.5K stars0 likes1 views
WebsiteGitHub

About

A .NET library for distributed synchronization

DistributedLock

DistributedLock is a .NET library that provides robust and easy-to-use distributed mutexes, reader-writer locks, and semaphores based on a variety of underlying technologies.

With DistributedLock, synchronizing access to a region of code across multiple applications/machines is as simple as:

csharp
await using (await myDistributedLock.AcquireAsync())
{
	// I hold the lock here
}

Implementations

DistributedLock contains implementations based on various technologies; you can install implementation packages individually or just install the DistributedLock NuGet package , a "meta" package which includes all implementations as dependencies. Note that each package is versioned independently according to SemVer.

  • DistributedLock.SqlServer (uses Microsoft SQL Server)
  • DistributedLock.Postgres (uses Postgresql)
  • DistributedLock.MySql (uses MySQL or MariaDB)
  • DistributedLock.Oracle (uses Oracle)
  • DistributedLock.Redis (uses Redis)
  • DistributedLock.Azure (uses Azure blobs)
  • DistributedLock.MongoDB (uses MongoDB)
  • DistributedLock.ZooKeeper (uses Apache ZooKeeper)
  • DistributedLock.FileSystem (uses lock files)
  • DistributedLock.WaitHandles (Windows only: uses operating system global WaitHandles)

Click on the name of any of the above packages to see the documentation specific to that implementation, or read on for general documentation that applies to all implementations.

The DistributedLock.Core package contains common code and abstractions and is referenced by all implementations.

Synchronization primitives

  • Locks: provide exclusive access to a region of code
  • Reader-writer locks: a lock with multiple levels of access. The lock can be held concurrently either by any number of "readers" or by a single "writer".
  • Semaphores: similar to a lock, but can be held by up to N users concurrently instead of just one.

While all implementations support locks, the other primitives are only supported by some implementations. See the implementation-specific documentation pages for details.

Basic usage

Names

Because distributed locks (and other distributed synchronization primitives) are not isolated to a single process, their identity is based on their name which is provided through the constructor. Different underlying technologies have different restrictions on name format; however, DistributedLock largely allows you to ignore these by escaping/hashing names that would otherwise be invalid.

Acquire

All synchronization primitives support the same basic access pattern. The Acquire method returns a "handle" object that represents holding the lock. When the handle is disposed, the lock is released:

csharp
var myDistributedLock = new SqlDistributedLock(name, connectionString); // e. g. if we are using SQL Server
using (myDistributedLock.Acquire())
{
	// we hold the lock here
} // implicit Dispose() call from using block releases it here

TryAcquire

While Acquire will block until the lock is available, there is also a TryAcquire variant which returns null if the lock could not be acquired (due to being held elsewhere):

csharp
using (var handle = myDistributedLock.TryAcquire())
{
	if (handle != null)
	{
		// we acquired the lock :-)
	}
	else
	{
		// someone else has it :-(
	}
}

async support

async versions of both of these methods are also supported. These are preferred when you are writing async code since they will not consume a thread while waiting for the lock. If you are using C#8 or higher, you can also dispose of handles asynchronously:

csharp
await using (await myDistributedLock.AcquireAsync()) { ... }

Timeouts

Additionally, all of these methods support an optional timeout parameter. timeout determines how long Acquire will wait before failing with a TimeoutException and how long TryAcquire will wait before returning null. The default timeout for Acquire is Timeout.InfiniteTimeSpan while for TryAcquire the default timeout is TimeSpan.Zero.

Cancellation

Finally, the methods take an optional CancellationToken parameter, which allows for the acquire operation to be interrupted via cancellation. Note that this won't cancel the hold on the lock once the acquire succeeds.

Providers

For applications that use dependency injection, DistributedLock's providers make it easy to separate out the specification of a lock's (or other primitive's) name from its other settings (such as a database connection string). For example in an ASP.NET Core app you might do:

…

Other topics

  • Interfaces
  • Detecting handle loss
  • Handle abandonment
  • Composite locks
  • Safety of distributed locking

Contributing

Contributions are welcome! If you are interested in contributing towards a new or existing issue, please let me know via comments on the issue so that I can help you get started and avoid wasted effort on your part.

Setup steps for working with the repository locally are documented here.

Release notes

  • 2.8.3
    • Bump MongoDB.Driver to avoid pulling in vulnerable packages (#281, DistributedLock.MongoDB 1.0.2). Thanks @Thynix for implementing!
  • 2.8.2
    • Fix support for Postgres instances with timeout settings using units other than millisecond (#277, DistributedLock.Postgres 1.3.1)
    • Reduce allocations in MongoDB locks (#276, DistributedLock.MongoDB 1.0.1). Thanks @joesdu for implementing!
  • 2.8.1
    • Fix connection monitoring query on Oracle. Thanks @matthew-marston for implementing! (#271, DistributedLock.Oracle 1.0.5)
    • Bump Microsoft.Data.SqlClient version (#273, DistributedLock.SqlServer 1.0.7)
    • Improve SqlDistributedSemaphore deadlock detection (#264, DistributedLock.SqlServer 1.0.7)
  • 2.8.0
    • Add MongoDB support! Thanks @joesdu for implementing! (#121, DistributedLock.MongoDB 1.0)
    • Add composite lock support. Thanks @moeen for implementing! (#236, DistributedLock.Core 1.0.9)
  • 2.7.1
    • Improve compatibility with Redis clusters that require keys in Lua scripts to be passed via the KEYS array. Thanks @pengweiqhca for reporting a identifying the fix! (#254, DistributedLock.Redis 1.1.1)
  • 2.7
    • Add support for fetching a Redis-based semaphore's current available count. Thanks @teesoftech for implementing! (#234, DistributedLock.Redis 1.1)
  • 2.6
    • Add support for acquiring transaction-scoped Postgres locks using externally-owned transactions. Thanks @Tzachi009 for implementing! (#213, DistributedLock.Postgres 1.3)
  • 2.5.1
    • Increase efficiency of Azure blob locks when the blob does not exist. Thanks @richardkooiman for implementing! (#227, DistributedLock.Azure 1.0.2)
    • Improve error handling in race condition scenarios for Azure blobs. Thanks @MartinDembergerR9 for implementing! (#228, DistributedLock.Azure 1.0.2)
    • Bump Microsoft.Data.SqlClient to 5.2.2 to avoid vulnerability. Thanks @steve85 for implementing! (#229, DistributedLock.SqlServer 1.0.6)
    • Bump Oracle.ManagedDataAccess to latest to avoid bringing in vulnerable packages (DistributedLock.Core 1.0.8, DistributedLock.Oracle 1.0.4)
    • Bump Npgsql to latest patch to avoid bringing in vulnerable packages (DistributedLock.Postgres 1.2.1)
    • Improve directory creation concurrency handling for FileDistributedLock (DistributedLock.FileSystem 1.0.3)
  • 2.5
    • Add support for creating Postgres locks off DbDataSource which is helpful for apps using NpgsqlMultiHostDataSource. Thanks davidngjy for implementing! (#153, DistributedLock.Postgres 1.2.0)
    • Upgrade Npgsql to 8.0.3 to avoid vulnerability. Thanks @Meir017/@davidngjy for implementing! (#218, DistributedLock.Postgres 1.2.0)
    • Fix Postgres race condition with connection keepalive enabled (#216, DistributedLock.Core 1.0.7)
    • Upgrade Microsoft.Data.SqlClient to 5.2.1 to avoid vulnerability (#210, DistributedLock.SqlServer 1.0.5)
  • 2.4
    • Add support for transaction-scoped locking in Postgres using pg_advisory_xact_lock which is helpful when using PgBouncer ([#168](https://github.com/madelson/DistributedLock/issues

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言