Beispiel #1
0
        public bool TryAcquire(TimeSpan timeout, CancellationToken token)
        {
            OneTimeWaiter waiter;

            lock (_lock)
            {
                if (_tokens > 0)
                {
                    _tokens--;
                    return(true);
                }

                token.ThrowIfCancellationRequested();

                _forTestingPurposes?.JustBeforeAddingToWaitQueue?.Invoke();

                waiter = new OneTimeWaiter(token);

                _waitQueue.Enqueue(waiter);
            }

            using (waiter)
            {
                bool result = waiter.TryWait(timeout);

                if (result == false)
                {
                    token.ThrowIfCancellationRequested();
                }

                return(result);
            }
        }
Beispiel #2
0
        public bool TryAcquire(TimeSpan timeout, CancellationToken token)
        {
            OneTimeWaiter waiter;

            lock (_lock)
            {
                if (_tokens > 0)
                {
                    _tokens--;
                    return(true);
                }

                token.ThrowIfCancellationRequested();

                _forTestingPurposes?.JustBeforeAddingToWaitQueue?.Invoke();

                waiter = new OneTimeWaiter();
                _waitQueue.Add(waiter);
            }

            using (waiter)
            {
                try
                {
                    var result = waiter.TryWait(timeout, token);
                    if (result == false)
                    {
                        RemoveWaiter(waiter);
                    }

                    return(result);
                }
                catch
                {
                    RemoveWaiter(waiter);

                    throw;
                }
            }

            void RemoveWaiter(OneTimeWaiter w)
            {
                lock (_lock)
                {
                    _waitQueue.Remove(w);
                }
            }
        }
Beispiel #3
0
        public bool TryAcquire(TimeSpan timeout, CancellationToken token)
        {
            OneTimeWaiter waiter;

            lock (_Lock)
            {
                if (_Tokens > 0)
                {
                    _Tokens--;
                    return(true);
                }

                waiter = new OneTimeWaiter();
                _waitQueue.Enqueue(waiter);
            }

            using (waiter)
            {
                return(waiter.TryWait(timeout, token));
            }
        }