Is this normal (avoids deadlocks, hunger, etc.) To try to get a lock in the sleep loop?

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)
        {
            // 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;
            }
        }
+3
source share
2 answers

Do you have the second part of the code locks requestCallbacksbefore locking with the method AcquireReaderLock()? If so, this could be a dead end.

. .

+2

, . ReaderWriterLockSlim ( ) - , . a) R-Lock W-Lock, , R W . b)

public void RequestQuote(string pS, QuoteRequestCallback pQrc) {
    Quote tQ;
    // acquire/release ReadLock inside TryGet
    if (TryGetQuote(pS, out tQ)) {
        pQrc(tQ);
    } else {
        // acquire/release WriteLock inside AddQuote
        // remark: I left the other collection
        // out since it seems unrelated to the actual problem
        AddQuote(new KeyValuePair(...)); // as above
    }
}
+2

All Articles