开发者

Have a class being created automatically when my app starts

Let's say I have a MySingleton class with a static constructor.

I want that singl开发者_如何学Goeton to be immediately to be created when my app start

Is there a way to do this without to have to code MySingleton.Instance.MyMethod when the app start ... just for the singleton to call the static constructor? I'm not so sure if this is possible but I'm throwing the question out there.

Thanks,


Is there a way to have an instance of a class created automatically when the app starts.

Yes. Put the creation logic in a static constructor, and then put Main in that class. The static constructor is always called before any method of the class, and Main is a method of the class.

If you can't put Main in that class then no. The static constructor will be triggered by (1) calling any static method on the class, or (2) creating an instance of the class.


No, instantiation will only occur as required based on initial member access.

Out of curiosity, why might you need it to be instantiated prior to it being needed at all?


From When is a static constructor in C# called?:

A static constructor is invoked by the first of either of the following conditions:

Create an instance of the class.
Refer any of the static methods of the class.

So if your constructor is both static and private, you'll have to refer to one of the methods. If not, you can just call the constructor.


AFAIK, there is no way of executing code from the loaded assembly. The calling assembly should reference this assembly by either instantiating a type from the assembly or calling a static method. Also, there is an Assembly Loaded event that you could use to execute code when a certain assembly was loaded, but as mentioned, you can only use this from the calling assembly (NOT the assembly being loaded). Probably the easiest way to start your timer is to call a static method like what the others have suggested.


Just call any method on the Singleton, and it will be instantiated.


If you want to call your static constructor directly, it's actually surprisingly easy.

In your main method, put the following code:

RuntimeHelpers.RunClassConstructor(typeof(MySingleton).TypeHandle);

This method is meant to only be used by compilers, though, so there might be some caveats I'm not aware of - I only know of the method because my own compiler needed to run class initializers at specific times.

Note: This method follows the initialization rules and makes sure that the initializer is never run twice, etc.


You can use a module initializer for that. Unfortunately, this CLR feature is not available in C#. But you can use a post-compiler like this one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜