What's the difference in these ways of creating the static instance for a singleton?

前端 未结 2 1729
栀梦
栀梦 2021-02-02 04:06

I have had a bug recently that only manifested itself when the library was built as a release build rather than a debug build. The library is a .NET dll with a COM wrapper and

相关标签:
2条回答
  • 2021-02-02 04:16

    Just reiterating what Marc Gravell said, but it sounds a lot like a beforefieldinit problem, which means the empty static constructor is your solution. You'd need to post any and all constructors in the class to get a definitive answer.

    The second method has the advantage of lazy loading (where that is an advantage).

    0 讨论(0)
  • 2021-02-02 04:42

    Try adding an (empty) static constructor, or initialize the singleton in a static constructor.

    Jon Skeet has a full discussion of singleton patterns here. I'm not sure why it failed, but at a guess it could relate to the "beforefieldinit" flag. See his 4th example, where he adds a static constructor to tweak this flag. I don't claim to be an expert on beforefieldinit, but this symptom seems to fit some of the symptoms discussed here.

    0 讨论(0)
提交回复
热议问题