Is New() inherently threadsafe?
-
I am trying to get an understanding about making classes thread-safe. Since the constructor is called just once for each instance of a class, does it follow that no other consideration needs to be given to ensure the constructor is thread-safe? Thanks for any help
-
I am trying to get an understanding about making classes thread-safe. Since the constructor is called just once for each instance of a class, does it follow that no other consideration needs to be given to ensure the constructor is thread-safe? Thanks for any help
Shayne Husson wrote: I am trying to get an understanding about making classes thread-safe. Since the constructor is called just once for each instance of a class, does it follow that no other consideration needs to be given to ensure the constructor is thread-safe? No. However the new Operator[^] is not the problem as it (as you already mentioned) just creates an object, invokes the constructor and returns a reference to the newly created object. This will be thread-safe as long as the constructor does not access any outside object (
public MyClass() {}
for example is no problem at all). But let's assume you have something like this:public MyClass(object someObject)
{
// some critical operation
}If you use this constructor in a multithreaded scenario you might end up having concurrent access of
someObject
. Now if you don't have a synchronization mechanism one thread might end up accessingsomeObject
in an inconsistent state. So ultimately the need for synchronization in the constructor really depends on if and what you're trying to do with any objects which are known outside the constructor. Best regards Dennis -
I am trying to get an understanding about making classes thread-safe. Since the constructor is called just once for each instance of a class, does it follow that no other consideration needs to be given to ensure the constructor is thread-safe? Thanks for any help
Just a little hint I forgot to mention in my previous post: when you dynamically create instances of anything derived from Control[^] be very careful in which thread you create them (see Multithreaded Windows Forms Control Sample[^] for details). Best regards Dennis
-
Just a little hint I forgot to mention in my previous post: when you dynamically create instances of anything derived from Control[^] be very careful in which thread you create them (see Multithreaded Windows Forms Control Sample[^] for details). Best regards Dennis
Cheers ;) that makes things clearer for me.