我試圖使用ReaderWriterLockSlim
類來管理列表。ReaderWriterLockSlim阻塞讀取,直到所有排隊的寫入完成
對這個列表有許多讀取和很少寫入,我的讀取速度很快,而我的寫入很慢。
我有一個簡單的測試工具,用來檢查鎖的工作方式。
如果發生以下情況
Thread 1 - Start Write
Thread 2 - Start Read
Thread 3 - Start Write
那麼結果如下
Thread 1 starts its write and locks the list.
Thread 2 adds itself to the read queue.
Thread 3 adds itself to the write queue.
Thread 1 finishes writing and releases the lock
Thread 3 aquires the lock and starts its write
Thread 3 finishes writing and releases the lock
Thread 2 performs its read
是否有換鎖的行爲的任何方式,使得被前排隊的任何讀請求寫鎖定被允許在寫鎖定被授予之前完成?
編輯:演示我的問題是下面
public partial class SimpleLock : System.Web.UI.Page
{
public static ReaderWriterLockSlim threadLock = new ReaderWriterLockSlim();
protected void Page_Load(object sender, EventArgs e)
{
List<String> outputList = new List<String>();
Thread thread1 = new Thread(
delegate(object output)
{
((List<String>)output).Add("Write 1 Enter");
threadLock.EnterWriteLock();
((List<String>)output).Add("Write 1 Begin");
Thread.Sleep(100);
((List<String>)output).Add("Write 1 End");
threadLock.ExitWriteLock();
((List<String>)output).Add("Write 1 Exit");
}
);
thread1.Start(outputList);
Thread.Sleep(10);
Thread thread2 = new Thread(
delegate(object output)
{
((List<String>)output).Add("Read 2 Enter");
threadLock.EnterReadLock();
((List<String>)output).Add("Read 2 Begin");
Thread.Sleep(100);
((List<String>)output).Add("Read 2 End");
threadLock.ExitReadLock();
((List<String>)output).Add("Read 2 Exit");
}
);
thread2.Start(outputList);
Thread.Sleep(10);
Thread thread3 = new Thread(
delegate(object output)
{
((List<String>)output).Add("Write 3 Enter");
threadLock.EnterWriteLock();
((List<String>)output).Add("Write 3 Begin");
Thread.Sleep(100);
((List<String>)output).Add("Write 3 End");
threadLock.ExitWriteLock();
((List<String>)output).Add("Write 3 Exit");
}
);
thread3.Start(outputList);
thread1.Join();
thread2.Join();
thread3.Join();
Response.Write(String.Join("<br />", outputList.ToArray()));
}
}
直接回答你的問題,「有沒有改變鎖的行爲的方法」,答案是否定的。 [ReaderWriterLockSlim]的文檔(http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx)說,「一個線程,如果有線程等待輸入寫入,則嘗試進入讀取模式塊模式下,或者在寫入模式下是否有單個線程。「目前還沒有辦法改變這種行爲。 –