Alex Rivera | Logout

How to Create a Thread-Safe Generic List?

Asked 2012-04-03T14:23:40.327
28

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?

Edit
Report

1 Answer

2

You will need to use locks in every place where the collection gets modified or iterated over.

Either that or use one of the new thread-safe data structures, like ConcurrentBag.

answered 2012-04-03T14:26:33.653

Your Answer