【发布时间】:2011-06-14 23:59:37
【问题描述】:
我正在使用 ReaderWriterLock 类来锁定作为 SortedDictionary 的 Quotes 集合。我正在考虑使用 while 循环,直到线程可以获取读取器锁,以防它被临时锁定以进行写入。第一个问题,我的测试运行良好,但是这种方法有缺点吗?第二个问题,这样做的最佳/最佳实践方式是什么?
public void RequestQuote(string symbol, QuoteRequestCallback qrc)
{
// add the call back on a list and take care of it when the quote is available
while (!AcquireReaderLock(100)) Thread.Sleep(150);
if (Quotes.ContainsKey(symbol))
{
qrc(Quotes[symbol]);
rwl.ReleaseReaderLock();
}
else
{
rwl.ReleaseReaderLock();
lock (requestCallbacks)
requestCallbacks.Add(new KeyValuePair<string, QuoteRequestCallback>(symbol, qrc));
// request symbol to be added
AddSymbol(symbol);
}
}
private bool AquireReaderLock(int ms)
{
try
{
rwl.AcquireReaderLock(ms);
return true;
}
catch (TimeoutException)
{
return false;
}
}
private bool AquireWriterLock(int ms)
{
try
{
rwl.AcquireWriterLock(ms);
return true;
}
catch (TimeoutException)
{
return false;
}
}
【问题讨论】:
-
如果
AcquireReaderLock永远不会返回 true 会怎样?你的程序是否保持一致的状态? -
如果 AcquireReaderLock 永远不会返回 true,则 RequestQuote 将陷入无限循环。我还要在编辑中粘贴它的代码。
-
好吧,我的意思是你不能假设它会。因此,如果超出了一定的重试次数,您需要一些机制来打破等待循环。
-
我明白了。说得通。因此,经过多次重试后,我会向请求程序集发送异常。
标签: c# .net multithreading deadlock