Reputation: 600
I have following code, which is confusing me a lot. The thing is that when static field abc will be initialized by CLR, it will be kinda instantiation of class ABC which will further instantiate class XYZ. My confusion is that in a multi-threaded environment before the threads do anything with the class Program and it's members, CLR would have already initialized field abc which means any threads trying to run DoSomething() method will have to share abc field (which is also an instance of ABC). Does this mean that class XYZ will only be instantiated once since when CLR initialized abc field just once and it's a shared field.
public class XYZ
{
public XYZ(string nameOfClass)
{
Console.WriteLine("XYZ ctor ran");
}
}
public class ABC
{
private XYZ xyz = null;
public ABC(string nameOfClass)
{
xyz = new XYZ(nameOfClass);
}
public void DoSomething()
{
Console.WriteLine("DoSomething Ran");
}
}
public class SomeClass
{
static ABC abc = new ABC("Program");
public void Helper()
{
abc.DoSomething();
}
}
public class Program
{
static void Main()
{
SomeClass sc = new SomeClass();
SomeClass sc2 = new SomeClass();
for (int i = 0; i < 20; i++)
{
new Thread(sc.Helper).Start();
}
sc2.Helper();
}
}
Upvotes: 0
Views: 60
Reputation: 152606
Does this mean that class XYZ will only be instantiated once since when CLR initialized abc field just once and it's a shared field.
Yes. There is only one instance of XYZ
since there is only one instance of ABC
.
I would note that none of the code that you posted shows any thread-unsafe code, so it's not clear what your concern is. It is possible that you could have multiple threads executing DoSomething
at the same time.
Upvotes: 1
Reputation: 4312
The static field is initialized at the first access to the class. See MSDN
A class is not initialized until its class constructor (static constructor in C#, Shared Sub New in Visual Basic) has finished running.To prevent the execution of code on a type that is not initialized, the common language runtime blocks all calls from other threads to static members of the class (Shared members in Visual Basic) until the class constructor has finished running.
Upvotes: 0