private ThreadLockState GetGlobalThreadState()
        {
            if (_currentThreadState == null)
            {
                Interlocked.CompareExchange(ref _currentThreadState, new Dictionary <int, ThreadLockState>(), null);
            }

            ThreadLockState state;

            if (!_currentThreadState.TryGetValue(_id, out state))
            {
                _currentThreadState[_id] = state = new ThreadLockState();
            }

            return(state);
        }
        private bool CheckState(ThreadLockState state, int millisecondsTimeout, LockState validState)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("ReaderWriterLockSlim");
            }

            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException("millisecondsTimeout");
            }

            // Detect and prevent recursion
            var ctstate = state.LockState;

            if (ctstate != LockState.None && _noRecursion && (!ctstate.Has(LockState.Upgradable) || validState == LockState.Upgradable))
            {
                throw new LockRecursionException("The current thread has already a lock and recursion isn't supported");
            }

            if (_noRecursion)
            {
                return(false);
            }

            // If we already had right lock state, just return
            if (ctstate.Has(validState))
            {
                return(true);
            }

            // In read mode you can just enter Read recursively
            if (ctstate == LockState.Read)
            {
                throw new LockRecursionException();
            }

            return(false);
        }