Home >Backend Development >C++ >How to Ensure Thread Safety with C# Static Constructors and Singleton Pattern?

How to Ensure Thread Safety with C# Static Constructors and Singleton Pattern?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-16 11:52:58934browse

How to Ensure Thread Safety with C# Static Constructors and Singleton Pattern?

Thread safety of C# static constructor

In C#, static constructors are executed only once per application domain before any class instance is created or static members are accessed. This ensures that they are thread-safe on initial construction, eliminating the need for locking and null testing during singleton object creation.

However, subsequent use of the instance may not be synchronous. To solve this problem, consider adding a static mutex to synchronize access to the instance.

The following is an example of a thread-safe singleton implementation that includes a mutex lock:

<code class="language-c#">public class Singleton
{
    private static Singleton instance;
    private static System.Threading.Mutex mutex = new System.Threading.Mutex(); // 初始化互斥锁
    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            mutex.WaitOne();
            try
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
    }
}</code>

This implementation uses the Instance attribute to synchronize access to the singleton instance, ensuring thread-safe operation for all subsequent usage scenarios. By using a get block within a try...finally accessor, you ensure that the mutex is released correctly even if an exception occurs. This is cleaner and safer than the Acquire() and Release() methods in the original example.

The above is the detailed content of How to Ensure Thread Safety with C# Static Constructors and Singleton Pattern?. 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