コード例 #1
0
        /// <summary>
        /// Try to get the actual file lock on behalf of the current request.
        /// </summary>
        /// <param name="currentRequest"></param>
        /// <returns></returns>
        private bool TryGetLock(DistributedLock currentRequest)
        {
            var waitForLock = currentRequest.WaitForLock;
            var lockTimeout = currentRequest.WaitTimeout;
            var validLock   = false;

            while (waitForLock == false || DateTimeOffset.Now < lockTimeout)
            {
                if (DateTimeOffset.Now >= _minTimeNextTurn) // Make sure we aren't in a back-off delay.
                {
                    var newLock = _provider.GetLock(_name);
                    if (newLock != null)
                    {
                        lock (_currentLockLock)
                        {
                            _lock = newLock;

                            // We have the lock!  Close our lock request if we have one so later we can detect if anyone else does.
                            if (_lockRequest != null)
                            {
                                _lockRequest.Dispose();
                                _lockRequest = null;
                            }
                        }

                        validLock = true; // Report that we have the lock now.
                    }
                }
                // Otherwise, just pretend we couldn't get the lock in this attempt.

                if (validLock == false && waitForLock)
                {
                    // We didn't get the lock and we want to wait for it, so try to open a lock request.
                    lock (_currentLockLock)
                    {
                        if (_lockRequest == null)
                        {
                            _lockRequest = _provider.GetLockRequest(_name); // Tell the other process we'd like a turn.
                        }
                    }

                    // Then we should allow some real time to pass before trying again because external locks aren't very fast.
                    Thread.Sleep(LockPollingDelay);
                }
                else
                {
                    // We either got the lock or the user doesn't want to keep retrying, so exit the loop.
                    break;
                }
            }

            return(validLock);
        }