C
C#5d ago
SWEETPONY

Should I use lock to update element of ConcurrentBag?

I have following code:
using System.Collections.Concurrent;

var obj = new object();

var test = new ConcurrentBag<UserConnection>
{
new()
{
Name = "John Doe",
IsActive = false
}
};

lock (obj)
{
test.First(x => x.Name == "John Doe").IsActive = true;
}

foreach (var t in test)
{
Console.WriteLine(new { t.Name, t.IsActive });
}

class UserConnection
{
public string Name { get; set; }
public bool IsActive { get; set; }
}
using System.Collections.Concurrent;

var obj = new object();

var test = new ConcurrentBag<UserConnection>
{
new()
{
Name = "John Doe",
IsActive = false
}
};

lock (obj)
{
test.First(x => x.Name == "John Doe").IsActive = true;
}

foreach (var t in test)
{
Console.WriteLine(new { t.Name, t.IsActive });
}

class UserConnection
{
public string Name { get; set; }
public bool IsActive { get; set; }
}
Is it important to use lock here? Is it worth to use Semaphore or Mutex here? All I want is a thread-safe update
2 Replies
SWEETPONY
SWEETPONYOP5d ago
or maybe I should use Interlocked? I don't understand why ConcurrentBag doesn't have thread-safe update methdo
canton7
canton75d ago
That's not what how you're supposed to use it It's intended that you have one or more threads (producers) throwing items into the bag, and one or more threads (consumers) taking items out of the bag for procesing. The bag doesn't have any order, so it's supposed to be for cases where the order of items doesn't matter The way you're using it, it looks like you want a ConcurrentDictionary<string, UserConnection>? Even with a ConcurrentDictionary, though, it won't protect you if you decide to mutate an item in the dictionary. You'll either have to use a separate lock, or have immutable objects

Did you find this page helpful?