I use the ReaderWriterLock class to lock the Quotes collection, which is a SortedDictionary. I am thinking about using a while loop until a thread can get a reader lock if it is temporarily locked for writing. The first question is, my tests work fine, but is there a flaw in this approach. The second question is, what is the best / best way to do this?
public void RequestQuote(string symbol, QuoteRequestCallback qrc)
{
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));
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;
}
}
bkarj source
share