Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a C# Constructor thread safe?

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?

like image 261
HelloPe Avatar asked May 21 '14 16:05

HelloPe


1 Answers

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)

like image 101
tooslow Avatar answered Oct 20 '22 15:10

tooslow