Locks in Single-Process Applications

In a single-machine environment, we can use thread locks to solve concurrency problems. In a distributed system, however, thread locks cannot solve concurrency problems, because a thread lock in a distributed system can only lock the current process, not other processes.

In .NET, we can use the lock keyword to implement a thread lock.

https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/statements/lock

private static readonly object _lock = new object();

public void DoSomething()
{
    lock (_lock)
    {
        // Business logic
    }
}

C# 13 introduces a new thread synchronization type, System.Threading.Lock, which simplifies lock usage through scope management, making the code clearer and more reliable.

using System.Threading.Lock;

private static readonly Lock _lock = new Lock();

public void DoSomething()
{
    using (_lock.EnterScope())
    {
        // Business logic
    }
}

Open-Source Distributed Lock Implementations

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

https://github.com/madelson/DistributedLock

Distributed Locks in the Zero Framework

The Zero Framework provides a basic abstraction for distributed locks and implements a distributed lock based on Dapr.

https://docs.dapr.io/developing-applications/building-blocks/distributed-lock/distributed-lock-api-overview

How the Redis Distributed Lock Works

The Redis distributed lock is implemented with the SETNX command. SETNX is an atomic Redis operation that sets a key’s value only if the key does not exist; if the key already exists, it does nothing.