静态变量的线程安全初始化 [英] Thread-safe initialization of static variables

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

问题描述

我一直在使用这种模式来初始化类中的静态数据.对我来说,它看起来是线程安全的,但是我知道线程问题可能会很细微.这是代码:

I've been using this pattern to initialize static data in my classes. It looks thread safe to me, but I know how subtle threading problems can be. Here's the code:

public class MyClass // bad code, do not use
{
    static string _myResource = "";
    static volatile bool _init = false;
    public MyClass()
    {
        if (_init == true) return;
        lock (_myResource)
        {
            if (_init == true) return;
            Thread.Sleep(3000); // some operation that takes a long time 
            _myResource = "Hello World";
            _init = true;
        }
    }
    public string MyResource { get { return _myResource; } }
}

这里有孔吗?也许有一种更简单的方法可以做到这一点.

Are there any holes here? Maybe there is a simpler way to do this.

更新:共识似乎是要使用静态构造函数.我使用静态构造函数提出了以下版本.

UPDATE: Consensus seems to be that a static constructor is the way to go. I came up with the following version using a static constructor.

public class MyClass
{
    static MyClass() // a static constructor
    {
        Thread.Sleep(3000); // some operation that takes a long time 
        _myResource = "Hello World";
    }

    static string _myResource = null;

    public MyClass() { LocalString = "Act locally"; } // an instance constructor

    // use but don't modify
    public bool MyResourceReady { get { return _myResource != null; } }
    public string LocalString { get; set; }
}

我希望这会更好.

推荐答案

您可以使用静态构造函数初始化您的静态变量,C#保证仅在每个AppDomain中调用一次.不知道您是否考虑过它们.

You can use static constructors to intialize your static variables, which C# guarantees will only be called once within each AppDomain. Not sure if you considered them.

因此您可以阅读以下内容: http://msdn.microsoft.com/en-us/library/aa645612(VS.71).aspx (静态构造函数)

So you can read this: http://msdn.microsoft.com/en-us/library/aa645612(VS.71).aspx (Static Constructors)

这是 C#静态构造函数线程安全吗?

这篇关于静态变量的线程安全初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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