C#C
C#10mo ago
6 replies
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; }
}


Is it important to use lock here? Is it worth to use Semaphore or Mutex here?
All I want is a thread-safe update
Was this page helpful?