Home > Mobile >  List RemoveRange Thread safety
List RemoveRange Thread safety

Time:01-30

I have a generic List that's getting added and removed by two different threads.

Thread 1 :

batchToBeProcessed = this.list.Count;
// Do some processing
this.list.RemoveRange(0, batchToBeProcessed.Count);

Thread 2 :

lock()
{
 this.list.Add(item);
}

Is RemoveRange, thread safe in the following scenario?

Say the list has 10 items thats being processed in thread1, and while removerange is getting executed, thread2 adds 1 item, what would happen?

Edit : Do not want to use a concurrentbag since I need the ordering.

CodePudding user response:

The answer to your question is No, it is not safe to have multiple threads modifying the list concurrently. You must synchronize access to the list using a lock or similar synchronization primitive. List is safe for multiple concurrent readers. Or you can have a single writer. But you can't modify the list in one thread while some other thread is accessing it at all.

As to what will happen if you try to Add while another thread is executing a RemoveRange, it's likely that the code will throw an exception. But it's possible no exception will be thrown and your list will become corrupted. Or it could work just fine. Which will happen depends on timing. But there's no guarantee that it will work.

To my knowledge, the .NET Framework does not have a concurrent data structure that gives you all the functionality of List.

CodePudding user response:

Is RemoveRange, thread safe in the following scenario?

No, all the methods in List<T> class are not thread safe.

Say the list has 10 items thats being processed in thread1, and while removerange is getting executed, thread2 adds 1 item, what would happen?

It's undefined, new item may be added to the end of the list, old items may not be removed, ...

CodePudding user response:

i think you should try ConcurrentBag<T> as they are thread safe

enter image description here

  • Related