-1

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?.

mahesh sharma
  • 998
  • 1
  • 7
  • 21

1 Answers1

1

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.
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • If I want to consume my concurrent queue parallely how could we do this? Is that right way what i am doing in above example. Please suggest – mahesh sharma Feb 09 '17 at 19:19
  • @maheshsharma code you have in the post achieves what you want. Is it actually useful for your task is up to you. You may want to ask separate question on better ways of achieving your actual goal (it is unlikely that whole point of your code is "to consume my concurrent queue parallely" - make sure to add real usage scenario if asking new question) – Alexei Levenkov Feb 09 '17 at 19:23