我有一个静态类,被多个远程调用和应用程序内的线程访问。这个类的部分功能是控制对各种文件的读写访问,因此我在文件列表上实现了一个静态ReaderWriterLock。该项目使用.NET Framework 2.0以满足客户需求。
但是,当我使用许多不同的客户端(通常使用16个)进行系统压力测试时,每个客户端都执行大量读写操作,然后在数小时甚至数天后,并且至少完成了500k+事务后系统会非常间歇性地崩溃。好吧,出现了一个bug..
但是当我检查所有锁定事件的日志时,我可以看到已经发生了以下情况:
1:线程A直接获取写锁,检查IsWriterLock显示为真。
2:线程B尝试获取读锁并成功,即使线程A仍然持有写锁
3:现在系统崩溃,堆栈跟踪现在显示ReaderWriterLock的空引用异常
之前已经运行了数十万次此过程而未出现错误,并且我可以检查日志并查看在所有先前的情况下读取锁定始终被阻止,直到写入退出。我还尝试将readerwriterlock实现为单例,但问题仍然存在。
以简化版本的readerwriterlock实现如下:
private const int readwriterlocktimeoutms = 5000;
private static ReaderWriterLock readerWriterLock = new ReaderWriterLock();
// this method will be called by thread A
public static void MethodA()
{
// bool to indicate that we have the lock
bool IsTaken = false;
try
{
// get the lock
readerWriterLock.AcquireWriterLock(readwriterlocktimeoutms);
// log that we have the lock for debug
// Logger.LogInfo("MethodA: acquired write lock; writer lock held {0}; reader lock held {1}", readerWriterLock.IsWriterLockHeld.ToString(),readerWriterLock.IsReaderLockHeld.ToString(), );
// mark that we have taken the lock
IsTaken = true;
}
catch(Exception e)
{
throw new Exception(string.Format("Error getting lock {0} {1}", e.Message, Environment.StackTrace));
}
try
{
// do some work
}
finally
{
if (IsTaken)
{
readerWriterLock.ReleaseWriterLock();
}
}
}
// this method will be called by thread B
public static void MethodB()
{
// bool to indicate that we have the lock
bool IsTaken = false;
try
{
// get the lock
readerWriterLock.AcquireReaderLock(readwriterlocktimeoutms);
// log that we have the lock for debug
// Logger.LogInfo("MethodB: acquired read lock; writer lock held {0}; reader lock held {1}", readerWriterLock.IsWriterLockHeld.ToString(),readerWriterLock.IsReaderLockHeld.ToString(), );
// mark that we have taken the lock
IsTaken = true;
}
catch (Exception e)
{
throw new Exception(string.Format("Error getting lock {0} {1}", e.Message, Environment.StackTrace));
}
try
{
// do some work
}
finally
{
if (IsTaken)
{
readerWriterLock.ReleaseReaderLock();
}
}
}
enter code here