OdeToCode IC Logo

Static Doesn't Mean Thread Safe

Thursday, October 19, 2006

One misunderstanding I often see is "if I make this member static it will be thread safe". I think this misconception arises because of the boilerplate MSDN documentation that will often say: "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

When a .NET framework class appears with the above documentation, it means a developer took the necessary precautions to make the static member thread safe. Perhaps they added a lock, or used some other synchronization mechanism to ensure thread safety. See: Statics and Thread Safety Part I and Part II.

Marking a class member static doesn't guarantee thread safety. It is up to you to make the member thread safe.

There is one exception to this rule. It's a special case where the static / Shared keyword will guarantee threading magic. Do you know what that is?