Giter Site home page Giter Site logo

Comments (2)

madelson avatar madelson commented on July 18, 2024 1

@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.

seiroga avatar seiroga commented on July 18, 2024 1

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.