Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# List RemoveRange Thread safety

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading