Search code examples
c#multithreadingdelegatesconcurrent-queue

Concurrent queue dequeue


I am using concurrent queue and dequeue the data from queue via multiple threads by creation Action delegate

Action action = () =>
        {
            SubscriptionResponseModel subsModel;
            while (concurrentQueue.TryTake(out subsModel))
            {
                MakeTransactionAndAddIntoQueue(subsModel);
            }
        };

And invoke this action delegate parallel multiple threads

Parallel.Invoke(action, action, action, action, action, action, action, action, action, action, action, action, action, action, action);

I want to know one thing when I am using SubscriptionResponseModel subsModel; in multiple actions is it thread safe?.


Solution

  • Each invocation of the action will have its own subsModel - so using it to get value from the queue is thread safe.

    Case when it would not be thread safe is when you capture variable from outside context:

        // ********** Code showing non-thread safe case **************
        SubscriptionResponseModel subsModel;
        Action action = () =>
        {
            // all invocations of `action` will share subsModel as it is captured.
            while (concurrentQueue.TryDequeue(out subsModel))
            {
                MakeTransactionAndAddIntoQueue(subsModel);
            }
        };
    

    Notes:

    • whether or not using properties/methods of the SubscriptionResponseModel is thread safe depends on that type.
    • there is a very good chance that running multiple TryDequeue in parallel will not improve performance at all. Parallel.Invoke of multiple busy loops will simply block more than one thread constantly querying empty queue.