17

I have gone through msdn where it is written that all the static classes are thread safe. Well that article is meant for version 1.1...

http://msdn.microsoft.com/en-us/library/d11h6832(v=vs.71).aspx

All public static members (methods, properties, fields, and events) within the .NET Framework support concurrent access within a multithreaded environment. Therefore, any .NET Framework static member can be simultaneously invoked from two threads without encountering race conditions, deadlocks, or crashes.

2
  • 2
    There is no hidden magic in the CLR that makes a writable member thread-safe. See here. Apr 30, 2011 at 6:21
  • @Paul Keister, u mean to say that all static methods, properties, fields, and events are thread safe ,as per the article.... Apr 30, 2011 at 6:40

2 Answers 2

20

What this is saying that all static members within .NET framework are designed in a thread safe way. That means that all the static methods / fields / properties developed by Microsoft for the .NET Framework. If you want to use a static member provided by .NET Framework itself, then you can assume it's thread safe and use it as such. I would still be suspicious of the validity of that statement though, and assume non-thread safety until proven otherwise.

Any classes that you write (static, or not) yourself and that have static members might or might not be thread safe depending on how you write them. It will not magically be thread safe just because it is a static method/class.

Also take a look at this to understand what are static members and what are static classes:

Static Classes and Static Members

0
15

No, it doesn't say that static classes are thread safe, it says that public static members are thread safe.

For static methods for example, this means that they only use the data that you send in as parameters, or other static members that are also thread safe.

You don't have to synchronise calls to static methods, unless it's needed to protect the data that you send into the method.

1
  • 1
    Am I correct to say that a static class and a singleton class, both are thread safe if they don't use any state? (by state I mean instance variables).
    – variable
    Jan 5, 2022 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.