6

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.

Joe
  • 40,031
  • 18
  • 107
  • 123
user4951
  • 31,039
  • 51
  • 162
  • 275

2 Answers2

10

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.

Mitch Wheat
  • 288,400
  • 42
  • 452
  • 532
3

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.

millimoose
  • 37,888
  • 9
  • 76
  • 132
  • 1
    True as this may be, this is boilerplate documentation that's on virtually every (if not every) .NET type. – Adam Robinson Jan 23 '12 at 02:04
  • Good to point out. That explains why there is no concurentList. List is already concurrent. +1 – user4951 Jan 23 '12 at 02:16
  • Actually no. There is no indicator that it's thread safe. List doesn't seem to contain any static method. – user4951 Jan 23 '12 at 02:19
  • 1
    @JimThio That's not what the documentation means. It means that if `List` had *static* methods, they would be threadsafe in that they wouldn't change any global state. It is *not* safe to share instances of `List` between threads without synchronisation, because you always need to call their instance methods to actually work with them. – millimoose Jan 23 '12 at 02:21
  • @JimThio You're looking for [`SynchronizedCollection`](http://msdn.microsoft.com/en-us/library/ms668265.aspx) – millimoose Jan 23 '12 at 02:22