Are Static classes thread safe

2019-02-16 08:57发布

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条回答
Melony?
2楼-- · 2019-02-16 09:11

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

查看更多
看我几分像从前
3楼-- · 2019-02-16 09:31

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.

查看更多
登录 后发表回答