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

How to Ensure Thread Safety in C# Static Constructors and Singleton Access?

DDD
Release: 2025-01-16 11:55:58
Original
579 people have browsed it

How to Ensure Thread Safety in C# Static Constructors and Singleton Access?

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template