是C#静态构造线程安全的? [英] Is the C# static constructor thread safe?

查看:145
本文介绍了是C#静态构造线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在换句话说,这是实现辛格尔顿线程安全的:

 公共类辛格尔顿
{
    私有静态Singleton实例;    私人辛格尔顿(){}    静态辛格尔顿()
    {
        例如=新辛格尔顿();
    }    公共静态Singleton实例
    {
        {返回实例; }
    }
}


解决方案

静态构造函数都保证每应用程序域只运行一次,会创建一个类的任何实例之前,或任何静态成员进行访问。 <一href=\"http://msdn.microsoft.com/en-us/library/aa645612.aspx\">http://msdn.microsoft.com/en-us/library/aa645612.aspx

中显示的实现是线程安全的初步建设,也就是说,需要构建Singleton对象没有锁定或空测试。然而,这并不意味着任何使用该实例的将被同步。有各种各样的,这是可以做到的方式;我已经展示了以下任一​​。

 公共类辛格尔顿
{
    私有静态Singleton实例;
    //添加静态互斥同步使用实例。
    私有静态System.Threading.Mutex互斥;
    私人辛格尔顿(){}
    静态辛格尔顿()
    {
        例如=新辛格尔顿();
        互斥=新System.Threading.Mutex();
    }    公共静态辛格尔顿采集()
    {
        mutex.WaitOne();
        返回实例;
    }    //每次调用获取()需要调用release()
    公共静态无效发行()
    {
        mutex.ReleaseMutex();
    }
}

In other words, is this Singleton implementation thread safe:

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}

解决方案

Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. http://msdn.microsoft.com/en-us/library/aa645612.aspx

The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.

public class Singleton
{
    private static Singleton instance;
    // Added a static mutex for synchronising use of 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;
    }

    // Each call to Acquire() requires a call to Release()
    public static void Release()
    {
        mutex.ReleaseMutex();
    }
}

这篇关于是C#静态构造线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆