Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are generic.list and generic.dictionary thread safe in .net

How do we know whether a method is thread safe or not

For example, if I check http://msdn.microsoft.com/en-us/library/3wcytfd1.aspx there is nothing that indicates its thread-safety.

like image 352
user4951 Avatar asked Jan 23 '12 01:01

user4951


2 Answers

No, they are not thread safe (without performing your own locking).

Use one of the Concurrent collections instead.

Thread-Safe Collections

The System.Collections.Concurrent namespace provides several thread-safe collection classes that should be used in place of the corresponding types in the System.Collections and System.Collections.Generic namespaces whenever multiple threads are accessing the collection concurrently.

like image 148
Mitch Wheat Avatar answered Oct 19 '22 23:10

Mitch Wheat


The documentation for the entire List<T> class has a segment on thread safety:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

like image 38
millimoose Avatar answered Oct 19 '22 23:10

millimoose