Home >Backend Development >C++ >Is C#'s Static Constructor Thread-Safe for Singleton Implementations?
Are C# static constructors thread-safe?
Consider the following singleton implementation:
<code class="language-csharp">public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } } }</code>
Is this implementation thread-safe?
Answer:
Static constructors (as shown in the example) are guaranteed to be run only once in the application domain, before any instance of the class is created or before the static members are accessed (https://www.php.cn /link/362c6840e40a65edd557a108c219f8f0).
Thus, the initial construction of a singleton instance is thread-safe, meaning it does not require locking or null testing. However, this does not guarantee that the singleton object can be used in a synchronous manner.
To achieve synchronization of any use of a singleton instance, several methods can be used. One method looks like this:
<code class="language-csharp">public class Singleton { private static Singleton instance; // 添加静态互斥体以同步实例的使用。 private static System.Threading.Mutex mutex; private Singleton() { } static Singleton() { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne(); return instance; } // 每次调用Acquire()都需要调用Release() public static void Release() { mutex.ReleaseMutex(); } }</code>
This implementation introduces static mutexes to synchronize access to singleton instances. To ensure proper synchronization, each instance's acquisition (Acquire()) must be released (Release()).
The above is the detailed content of Is C#'s Static Constructor Thread-Safe for Singleton Implementations?. For more information, please follow other related articles on the PHP Chinese website!