JD.
JD.

Reputation: 15551

Changing object in a ConcurrentBag?

I read that to modify or mutate an object in a concurrent bag I have to take it out, modify it and then put it back in.

However, I have seen code that does the following:

var obj = bag.FirstOrDefault(report => report.id == id);
obj.name = 'Change to something else';

where Report is a object type that the bag holds.

Now this seems to work. Is this correct though?

Upvotes: 2

Views: 3620

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103467

It works, but it's not thread-safe. See the docs:

All public and protected members of ConcurrentBag<T> are thread-safe and may be used concurrently from multiple threads. However, members accessed through one of the interfaces the ConcurrentBag<T> implements, including extension methods, are not guaranteed to be thread safe and may need to be synchronized by the caller.

In other words, in order to modify or mutate an object in a concurrent bag in a thread-safe manner you have to take it out, modify it and then put it back in.

Upvotes: 6

Related Questions