Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a Thread-Safe Generic List?

Tags:

I have a Generic List as below

public static readonly List<Customer> Customers = new List<Customer>(); 

I'm using the below methods for it:

.Add .Find .FirstOrDefault 

The last 2 are LINQ extensions.

I'd need to make this thread-safe to be able to run multiple instances of the container class.

How to achieve that?

like image 307
The Light Avatar asked Apr 03 '12 14:04

The Light


People also ask

How do you make a thread-safe set?

This method accepts an object of Set interface and, returns a synchronized (thread-safe) set backed by the specified set. This method accepts an object of the Map interface and, returns a synchronized (thread-safe) sorted map backed by the specified sorted map.

How do you make a list thread-safe in Java?

A thread-safe variant of ArrayList in which all mutative operations (e.g., add, set, remove..) are implemented by creating a separate copy of an underlying array. It achieves thread safety by creating a separate copy of the List which is different than vector or other collections used to provide thread-safety.

How can I make a list thread-safe in C#?

Thread Safe List With the ConcurrentBag Class in C# The ConcurrentBag class is used to create a thread-safe, unordered collection of data in C#. The ConcurrentBag class is very similar to the List in C# and can be used as a thread-safe list in C#. To use the ConcurrentBag class, we have to import the System.

Is list Addrange thread-safe?

No it is not thread-safe.


1 Answers

If those are the only functions you are using on List<T> then the easiest way is to write a quick wrapper that synchronizes access with a lock

class MyList<T> {    private List<T> _list = new List<T>();   private object _sync = new object();   public void Add(T value) {     lock (_sync) {       _list.Add(value);     }   }   public bool Find(Predicate<T> predicate) {     lock (_sync) {       return _list.Find(predicate);     }   }   public T FirstOrDefault() {     lock (_sync) {       return _list.FirstOrDefault();     }   } } 

I highly recommend the approach of a new type + private lock object. It makes it much more obvious to the next guy who inherits your code what the actual intent was.

Also note that .Net 4.0 introduced a new set of collections specifically aimed at being used from multiple threads. If one of these meets your needs I'd highly recommend using it over rolling your own.

  • ConcurrentStack<T>
  • ConcurrentQueue<T>
like image 163
JaredPar Avatar answered Oct 11 '22 14:10

JaredPar