Thread safety of C# static constructor
In C#, a static constructor is executed before any instance initialization or static member access of a class. Therefore, it guarantees the thread safety of the initial construction of the singleton.
Initial construction is safe
The provided singleton implementation guarantees this initial phase is thread-safe as it does not rely on locking or null testing.
Instance access security
However, this does not guarantee that subsequent use of the instance will be synchronized. To solve this problem, the following improvements can be made:
<code class="language-csharp">public class Singleton { // 添加静态互斥锁以同步对实例的访问 private static System.Threading.Mutex mutex; private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne(); return instance; } public static void Release() { mutex.ReleaseMutex(); } }</code>
Enforce thread safety
This modified implementation uses a static mutex to synchronize access to the instance, ensuring that only one thread can access it at a time. To use a singleton, a thread must call the Acquire()
method to obtain the instance and call the Release()
method when finished.
The above is the detailed content of How to Ensure Thread Safety in C# Static Constructors and Singleton Access?. For more information, please follow other related articles on the PHP Chinese website!