System.Threading.ReaderWriterLockSlim.TryEnterReadLock C# (CSharp) Method

TryEnterReadLock() public method

public TryEnterReadLock ( int millisecondsTimeout ) : bool
millisecondsTimeout int
return bool
		public bool TryEnterReadLock (int millisecondsTimeout)
		{
			if (millisecondsTimeout < Timeout.Infinite)
				throw new ArgumentOutOfRangeException ("millisecondsTimeout");
			
			if (read_locks == null)
				throw new ObjectDisposedException (null);

			if (Thread.CurrentThread == write_thread)
				throw new LockRecursionException ("Read lock cannot be acquired while write lock is held");

			EnterMyLock ();

			LockDetails ld = GetReadLockDetails (Thread.CurrentThread.ManagedThreadId, true);
			if (ld.ReadLocks != 0) {
				ExitMyLock ();
				throw new LockRecursionException ("Recursive read lock can only be aquired in SupportsRecursion mode");
			}
			++ld.ReadLocks;
			
			while (true){
				// Easy case, no contention
				// owners >= 0 means there might be readers (but no writer)
				if (owners >= 0 && numWriteWaiters == 0){
					owners++;
					break;
				}
				
				// If the request is to probe.
				if (millisecondsTimeout == 0){
					ExitMyLock ();
					return false;
				}

				// We need to wait.  Mark that we have waiters and wait.  
				if (readEvent == null) {
					LazyCreateEvent (ref readEvent, false);
					// since we left the lock, start over. 
					continue;
				}

				if (!WaitOnEvent (readEvent, ref numReadWaiters, millisecondsTimeout))
					return false;
			}
			ExitMyLock ();
			
			return true;
		}

Same methods

ReaderWriterLockSlim::TryEnterReadLock ( TimeSpan timeout ) : bool

Usage Example

Example #1
0
 public ReadOnlyLock(ReaderWriterLockSlim rwl, int millisecondsTimeout)
     : base(rwl)
 {
     if (millisecondsTimeout == Timeout.Infinite)
     {
         while (!_lockAcquired)
             _lockAcquired = rwl.TryEnterReadLock(1);
     }
     else
     {
         _lockAcquired = rwl.TryEnterReadLock(millisecondsTimeout);
     }
 }
All Usage Examples Of System.Threading.ReaderWriterLockSlim::TryEnterReadLock