How to initialize a C# static class before it is actually needed?

后端 未结 5 1428
北海茫月
北海茫月 2021-02-05 10:54

I have a static class with a static constructor that takes some time (10-15 seconds) to execute and fully initialize the class. In order to improve performance, I\'ve decided to

5条回答
  •  萌比男神i
    2021-02-05 11:21

    I would go with the initialize method (EDIT: See Jon's answer). But if you really just want to use the constructor, you can do this:

    var type = typeof (YourType);
    System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
    

    RunClassConstructor allows you to force the class constructor (static constructor) to run if it already hasn't. If it has already run, say because you used a static member of the class, then this has no effect. Running it additional times has no effect.

提交回复
热议问题