0

Can anyone tell me if the following code is thread-safe in C#:

ConcurrentBag cb = new ConcurrentBag();
Parallel.ForEach(someCollection, (param1) => 
{`
    `cb.Add(GetOutput(param1));
});

private SomeClass GetOutput(InputParameter param1)
{
    SomeClass someClassInstance = null;
    //declare local variables;

    //call an external service;
    return someClassInstance;
}

There is no shared state across iterations and the iterations are independent. My doubt is around the GetOutput private method and the local variables declared in it. Will they be allocated separately for each thread? I am 99.99% sure they will be, but wanted to seek expert opinion.

Thanks

Vikas

Viking22
  • 545
  • 1
  • 7
  • 19
  • Just a FYI, you appear to have a pure Producer-Consumer scenario, `ConcurrentQueue` will perform better than a `ConcurrentBag` [in that situation](https://msdn.microsoft.com/en-us/library/dd997373(v=vs.110).aspx), the only time you should use `ConcurrentBag` is when you are developing something that has a "Object pool" like behavior where many threads are both adding and removing to the collection. If you have separate threads adding and removing the queue performs better. – Scott Chamberlain Jun 01 '17 at 20:20

2 Answers2

1

Yes, any variables declared within the scope of the method will be allocated for each call regardless of whether concurrent threads are calling the method.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
1

My doubt is around the GetOutput private method and the local variables declared in it. Will they be allocated separately for each thread?

Yes.

Each invocation of the GetOutput method will always gets its own independent local variables. A local variable may still refer to an object which another thread may use simultaneously though. But as long as your data is local, the method is thread-safe.

Please refer to the answers in the following similar question for more information about this.

Are local variables threadsafe?

mm8
  • 163,881
  • 10
  • 57
  • 88