Ejemplo n.º 1
0
        public Task <IDisposable> GetLock(T key)
        {
            LockItem nextLi = new LockItem(locks, key);

            try
            {
                bool continueImmediately = false;
                lock (locks)
                {
                    LockItem li;
                    if (!locks.TryGetValue(key, out li))
                    {
                        locks.Add(key, nextLi);
                        continueImmediately = true;
                    }
                    else
                    {
                        while (li.Next != null)
                        {
                            li = li.Next;
                        }

                        li.Next = nextLi;
                    }
                }
                if (continueImmediately)
                {
                    nextLi.Continue();
                }
            }
            catch (Exception e)
            {
                nextLi.Error(e);
            }
            return(nextLi.GetTask());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Waits for and acquires a lock on the specified key. Dispose the returned value to release the lock.
        /// </summary>
        /// <param name="key"></param>
        public Task <IDisposable> GetLock(T key)
        {
            // ReSharper disable once InconsistentlySynchronizedField - by design
            var nextLi = new LockItem(locks, key);

            try
            {
                var continueImmediately = false;
                lock (locks)
                {
                    if (!locks.TryGetValue(key, out var li))
                    {
                        locks.Add(key, nextLi);
                        continueImmediately = true;
                    }
                    else
                    {
                        while (li.Next != null)
                        {
                            li = li.Next;
                        }

                        li.Next = nextLi;
                    }
                }
                if (continueImmediately)
                {
                    nextLi.Continue();
                }
            }
            catch (Exception e)
            {
                nextLi.Error(e);
            }
            return(nextLi.GetTask());
        }