none
Efficient approach to thread sync

    Question

  • I have an API I have wrapped that requires synchronous access. The easy solution was to create a concurrent queue and add work to it while a thread processed what ever came through. Scenario has changed, during what might be millions of continuously accumulating queued bulk calls, I need to interrupt and perform a different call from another thread then allow the queue to resume every so often.

    I am not sure using a myriad of wait handles and signalling instead of locking is actually faster than a traditional lock as I doubt I could do a better job than the BCL authors. Am I correct in assuming that the queue should simply loop through endlessly with cancellation checks and repeated locks, there is no more efficient approach?

    Probably a SemaphoreSlim(1, 1) instance with try/finally semantics to ensure operational integrity is the best option here as it offers overloads which respond to cancellation, despite the magnitude of wait/release cycles the queue would invoke.
    • Edited by Ritmo2k Wednesday, March 29, 2017 9:20 PM
    Wednesday, March 29, 2017 8:47 PM

Answers

  • Simplicity should be the priority in all things, but especially here where there is an API call involved, which is probably pretty slow anyway.  So yes, using a lock to pre-empt the queue reader thread is a simple (good) pattern. 

    If you use a lock, put it around only the API call, not the queue read.  EG both the queue reader and any synchronous calls access the API through a synchronized method, like:

            public void CallApi(MyApiRequest data)
            {
                lock(synclock)
                {
                    ///actually call the API
                }
            }

    David


    Microsoft Technology Center - Dallas
    My blog


    Wednesday, March 29, 2017 10:01 PM