Home >Backend Development >C++ >Is a C# Singleton with a Static Constructor Thread-Safe?

Is a C# Singleton with a Static Constructor Thread-Safe?

DDD
DDDOriginal
2025-01-16 11:27:59853browse

Is a C# Singleton with a Static Constructor Thread-Safe?

Singleton thread safety issues in C# static constructor

This article explores whether C# singleton classes implemented using static constructors are thread-safe, and how to ensure that only one instance exists in a multi-threaded environment.

Initial construction

Static constructors are executed only once in the application domain, before the class is instantiated or the static members are accessed. Therefore, the initial construction of a singleton instance is thread-safe.

Follow-up visit

However, it is critical to ensure that access after initial construction is thread-safe. The provided implementation allows multiple threads to access the singleton instance simultaneously, potentially causing problems.

Synchronization mechanism

To solve this problem, the implementation can be enhanced using a synchronization mechanism. One way is to add a static mutex like this:

<code class="language-c#">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;
    }

    // 释放互斥锁,允许其他线程访问实例。
    public static void Release()
    {
        mutex.ReleaseMutex();
    }
}</code>

How to use

In order to safely access a singleton instance, a thread must first acquire a mutex using the Acquire() method. Once completed, the Release() method will unlock the mutex, allowing other threads to access the instance.

Conclusion

By adding a synchronization mechanism, the singleton implementation becomes thread-safe, eliminating potential concurrency issues.

The above is the detailed content of Is a C# Singleton with a Static Constructor Thread-Safe?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn