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?
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.
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.
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.
No it is not thread-safe.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With