Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static variables initialized in any particular thread?

Tags:

c#

windows

I was doing some research inspired by this question and I noticed that several of the proposed solutions to similar problems created a mutex object during initialization of a static variable. Such a mutex will only work as desired if the thread that created it remains alive for the lifetime of the application.

Now it seems a reasonable guess that static variables are initialized by the process main thread, and it also seems a reasonable guess that the process main thread only exits when the main function exits (which is presumably under the control of the programmer).

But are either of these actually guaranteed by the C# language standard?

PS: I'm talking about Windows threads, not .NET threads.

like image 860
Harry Johnston Avatar asked Sep 12 '15 20:09

Harry Johnston


1 Answers

In C#, static variables are initialized by the class loader when the class is first loaded. This has the interesting artifact of being on whatever thread first referenced the class.

We also note that the main thread is not guaranteed to be a managed thread, so any library after the main thread isn't quite guaranteed to be able to identify it. I wrote a program once that had no main thread after native initialization just to prove it could be done.

like image 61
Joshua Avatar answered Oct 20 '22 12:10

Joshua