Comments (2)
@seiroga while SQL supports this, it only works if you acquire using the same SqlConnection for each acquire request (otherwise, SQL has no way of knowing that you're the same caller). In the 1.x series I believe this works if you construct a lock using an explicit connection, however I consider this to be a bug/surprising behavior and as such 2.0 is never reentrant.
The challenge with reentrancy and distributed locking in general is that reentrance requires some notion of what "context" owns the lock, and in a distributed scenario it isn't obvious what that would be. Traditionally, reentrance might be available on the same thread (e. g. for native .NET locks), but this falls apart once you start using async methods.
If you want this behavior, I'd suggest building it yourself as a wrapper around the underlying distributed lock. This is also more efficient since it avoids unnecessary calls to SQL. Here's an example which defines the "context" for reentrancy based on the current thread (requires using only synchronous methods). With some additional work, you could make this logical-flow-of-control-based (would support async/await) using SemaphoreSlim and AsyncLocal. Note that I haven't tested this, but it should give you the right idea:
class ReentrantByThreadDistributedLock
{
// global mapping of names to monitors. If you'll use a lot of names, this will be a memory leak. You could solve this
// by making the dictionary store names => WeakReference<MonitorHandle> and creating a background thread that
// deletes entries from the dictionary where the weak reference isn't alive every 30s or so.
private static readonly Dictionary<string, MonitorHandle> MonitorHandlesByName = new Dictionary<string, MonitorHandle>();
private readonly SqlDistributedLock _distributedLock;
private readonly string _name;
public ReentrantByInstanceDistributedLock(string name, string connectionString)
{
this._distributedLock = new SqlDistributedLock(name, connectionString);
this._name = name;
}
public IDisposable? TryAcquire(TimeSpan timeout, CancellationToken cancellationToken)
{
// get the monitor handle for our name
MonitorHandle monitorHandle;
lock (MonitorHandlesByName)
{
if (!MonitorHandlesByName.TryGetValue(this._name, out monitorHandle))
{
MonitorHandlesByName.Add(this._name, monitorHandle = new MonitorHandle());
}
}
bool acquired = false, monitorTaken = false;
try
{
// attempt to acquire the monitor for our thread. Will succeed if our thread already holds it
Monitor.TryEnter(monitorHandle.Monitor, timeout, ref monitorTaken);
if (!monitorTaken) { return null; }
// If you want to be really precise with your timeouts, you should time how long
// it takes to acquire the monitor and subtract that from the time taken to acquire
// the distributed lock
lock (monitorHandle) // this lock is important for releasing safely
{
// only acquire the distributed handle if we don't already have it
monitorHandle.DistributedLockHandle ??= this._distributedLock.TryAcquire(timeout, cancellationToken);
if (monitorHandle.DistributedLockHandle != null)
{
acquired = true;
return new Handle(monitorHandle);
}
}
}
// if we failed to acquire, don't hold the monitor
finally { if (!acquired && monitorTaken) { Monitor.Exit(monitorHandle.Monitor); } }
return null;
}
private class MonitorHandle
{
public object Monitor { get; } = new object();
public IDisposable? DistributedLockHandle { get; set; }
}
private class Handle : IDisposable
{
private MonitorHandle? _monitorHandle;
public Handle(MonitorHandle monitorHandle) { this._monitorHandle = monitorHandle; }
public void Dispose()
{
var monitorHandle = Interlocked.Exchange(ref this._monitorHandle, null);
if (monitorHandle != null)
{
lock (monitorHandle)
{
// exit the monitor
Monitor.Exit(monitorHandle.Monitor);
// if we were the last to exit, release the distributed lock
if (!Monitor.IsEntered(monitorHandle.Monitor))
{
var distributedLockHandle = monitorHandle.DistributedLockHandle;
monitorHandle.DistributedLockHandle = null; // do this first in case dispose fails
distributedLockHandle!.Dispose();
}
}
}
}
}
}
from distributedlock.
Thanks for your explanation!
I understand that with different SQL connections it will not work.
I proposing to use SQL connection as a context for such reentrancy not metter on which thread call was made at all.
So the use case is call TryAcquire/TryAcquireAsync on same SqlDistributedLock instance.
But you have provided valuable argument about performance: "I'd suggest building it yourself as a wrapper around the underlying distributed lock. This is also more efficient since it avoids unnecessary calls to SQL." 👍
Thanks for example provided and your time!
from distributedlock.
Related Issues (20)
- FileDistributedLock - Use FileSystemWatcher to optimize wait
- Where locks are stored when using Postgres HOT 3
- Postgres lock is not released in specific multi-threaded scenarios HOT 13
- Timeouts seems not work in DistributedLock.Redis HOT 5
- Update minimum SqlClient versions to avoid vulnerability HOT 2
- Postgres: consider leveraging batching for efficiency (newer versions only)
- Postgres: consider switching to positional parameter style
- Postgres: consider constructor with NpgsqlDatasource
- ZooKeeperNetEx connection loss issue: an acquired lock seems is not released HOT 50
- Azure: create the container on the fly if it does not exist HOT 4
- Increase in lost lock after upgrading to .NET 7, EF Core 7 and Microsoft.Data.SqlClient 5.0.1 HOT 21
- Add custom data to AzureBlobLeaseDistributedLock HOT 10
- Redis: RedisScript (LuaScript) execution error - CultureInfo problem HOT 7
- DistributedLock.Azure: Remove MaxNonInfiniteLeaseDuration HOT 2
- Use Distributed lock to manage multiple calls to the same Azure function HOT 2
- Postgres distributed lock using PgBouncer connection pooler HOT 8
- About Distribute Locking System using Redis HOT 2
- RobiniaDocs API Explorer HOT 8
- Postgres - Multiple threads successfully acquire the same lock HOT 3
- Concurrency with Redis Semaphore HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from distributedlock.