I found strange behaviour for ReaderWriterLock. If I call method AcquireWriterLock and then after this in the same thread call method AcquireReaderLock with ReleaseReaderLock, method RelaseWriterLock will not release ReaderWriterLock and WriterLock will stay alive.
Is anybody know is this a bug or a feature
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace QuickTest
{
static class Program
{
private static ReaderWriterLock _rwl = new ReaderWriterLock();
/// <summary>
/// The main entry point for the application.
/// </summary>
[MTAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
TestReaderTimeOutException();
}
private static void TestReaderTimeOutException()
{
//1. Make thread which will lock ReaderWriteLock
Thread thre = new Thread(new ThreadStart(LockWriter));
thre.Start();
//2. Make thread whick try to acquire ReaderWriteLock and throw timeout
Thread thre2 = new Thread(new ThreadStart(LockReader));
thre2.Start();
//Wait 60 second
thre.Join();
}
private static void LockWriter()
{
try
{
_rwl.AcquireWriterLock(10000);
LockReader();
}
finally
{
if (_rwl.IsWriterLockHeld)
{
_rwl.ReleaseWriterLock(); //NOT RELEASE WRITER LOCK!
}
}
}
private static void LockReader()
{
try
{
try
{
_rwl.AcquireReaderLock(20000);
}
finally
{
if (_rwl.IsReaderLockHeld)
{
//Try to relase lock which is not held
_rwl.ReleaseReaderLock();
}
}
}
catch (Exception ex) //!!!
{
Debug.Fail(ex.ToString());
}
finally
{
Debug.WriteLine("...");
}
}
}
}