I am using the ReaderWriterLock class to lock a Quotes collection which is a SortedDictionary. I am thinking of using a while loop until a thread can acquire the reader lock in case it is temporarily locked for writing. First question, my tests are working fine, but is there a drawback to this approach. Second question, what’s the optimal/best-practice way of doing this?
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;
}
}
Do you have a second piece of code locks
requestCallbacksbefore locking with theAcquireReaderLock()method? If so, it can deadlock with this.Adding loops and sleep delays to avoid deadlocks won’t work in the general case. A strict hierarchy of lock acquisition will work in the general case.