Is a C# Constructor thread safe?

帅比萌擦擦* 提交于 2020-01-01 09:36:07

问题


Let's say I have multiple threads and each of them is trying to create objects of the same class.
Will the simultaneous creation of objects of the same type in different threads interfere with each other? Do I need to use "lock" within the constructor?


回答1:


This depends very much on the implementation of the constructor.

If the constructor is only accessing members of that class, and not any external static classes or methods, then yes - it is thread safe.

But if that constructor is accessing non-threadsafe objects that exist outside of the class itself, (such as a global singleton), then it is not threadsafe.

update: The constructor should be careful not to access any static members of the class that are not readonly or const. (thanks Nathan A and LVBen)



来源:https://stackoverflow.com/questions/23789106/is-a-c-sharp-constructor-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!