public void CanEnterLocksSync()
        {
            var myLock = new AsyncReaderWriterLockSlim();

            myLock.EnterReadLock();
            Assert.IsTrue(myLock.TryEnterReadLock(0));
            Assert.IsFalse(myLock.TryEnterWriteLock(0));
            myLock.ExitReadLock();
            myLock.ExitReadLock();

            myLock.EnterWriteLock();
            Assert.IsFalse(myLock.TryEnterReadLock(0));
            Assert.IsFalse(myLock.TryEnterWriteLock(0));
            myLock.ExitWriteLock();
        }
        public async Task WriteTakesPriorityOverRead1()
        {
            var myLock = new AsyncReaderWriterLockSlim();

            // Check that no new read lock can be entered when another thread/task wants
            // to enter the write lock while at least one read lock is active.
            myLock.EnterReadLock();

            using (var cts = new CancellationTokenSource())
            {
                var enterWriteLockTask = myLock.EnterWriteLockAsync(cts.Token);

                Assert.IsFalse(myLock.TryEnterReadLock(0));

                cts.Cancel();
                try
                {
                    await enterWriteLockTask;
                    Assert.Fail();
                }
                catch (OperationCanceledException)
                {
                }
            }

            // Verify that now a new read lock can be entered.
            Assert.IsTrue(await myLock.TryEnterReadLockAsync(0));
        }
        public void DowngradeLockAllowsReadLock()
        {
            var myLock = new AsyncReaderWriterLockSlim();

            myLock.EnterWriteLock();

            Assert.IsFalse(myLock.TryEnterWriteLock(0));
            Assert.IsFalse(myLock.TryEnterReadLock(0));

            // After downgrading the lock and after the try to get the write lock is canceled,
            // it should be possible to enter another read lock.
            myLock.DowngradeWriteLockToReadLock();

            Assert.IsFalse(myLock.TryEnterWriteLock(0));
            Assert.IsTrue(myLock.TryEnterReadLock(0));

            myLock.ExitReadLock();
            myLock.ExitReadLock();
        }
        public void ThrowsOperationCanceledExceptionAfterWait()
        {
            var myLock = new AsyncReaderWriterLockSlim();

            myLock.EnterReadLock();

            try
            {
                using (var cts = new CancellationTokenSource(100))
                {
                    myLock.EnterWriteLock(cts.Token);
                }
            }
            catch (OperationCanceledException)
            {
                // Check that we can now enter another read lock.
                Assert.IsTrue(myLock.TryEnterReadLock(0));

                throw;
            }
        }