Search code examples
c#multithreading.net-2.0

List<T> multiple writer thread safety


If I have multiple threads calling the Add method of a List object, and no readers, do I only need to lock on the List object before calling Add to be thread safe?


Solution

  • Usually it's best to lock on a separate (immutable) object... locking on the same object you're modifying is bad practice should be done with caution.

    private readonly object sync = new object();
    private List<object> list = new List<object>();
    
    void MultiThreadedMethod(object val)
    {
        lock(sync)
        {
            list.Add(val);
        }
    }
    

    In a basic case like this you will not have a problem, but if there is a possibility that your list can be changed (not the contents of the list, but the list itself), then you might have a situation where you lock on two objects when you only intend to lock on one.