Home > front end >  Do I have to use Thread-safe Collections?
Do I have to use Thread-safe Collections?

Time:11-11

Do I have to use concurrent types in MethodTwo.

if I don't, can my list (anotherList) is completely saved with true values?

public void MethodOne(List<int> idList)
{
    foreach (int id in IdList)
    {
         var Item = GetById(id);
         System.Threading.Tasks.Task.Run(() => MethodTwo(item.PropOne));
    }
}

public void MethodTwo(int prop)
{
    List<string> anotherList = new List<string>();
    anotherList.Add("AAA");
        
    if (prop>20)
        anotherList.Add("BBB");
    else
        anotherList.Add("CCC");

    //some other operations

    SaveList(anotherList);
}

There is a bug but I can not catch it. I am suspicious about this method. I tried load test on this method and I could not get any information.

CodePudding user response:

No

Thread safety is a concern whenever multiple threads may write to the same data, or reading and writing, at the same time.

If your list is only accessed by a single thread it is perfectly safe to use a regular list.

This is often used when writing asynchronous code, a typical pattern might look something like:

int[] data = new int[]{1, 2, 3};
var result = await Task.Run(MyMethod);
// Use result
...

int[] MyMethod(int[] data ){
    // Do some processing
    return new int[]{4, 5, 6};
}

While the data-array is shared, it is perfectly safe as long as it is not modified.

If we change the example to do concurrent reading and writing we would be in trouble:

int[] data = new int[]{1, 2, 3};
var task = Task.Run(MyMethod);
data[0] = 42; // Writing shared data concurrently with reading. Unsafe!
var result = await task;
// Use result
...

int[] MyMethod(int[] data ){    
    var d = data[0]; // Reading shared data concurrently with writing. Unsafe!
    // Do some processing
    return new int[]{d, 5, 6};
}

Since we now have both reading and writing that may be done at the same time, the code is unsafe. This could be fixed by a lock, but it is typically a better idea to try to avoid shared mutable state as much as possible in the first place.

  • Related