加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 一个构造函数可以被抢占吗?

发布时间:2020-12-15 18:01:19 所属栏目:百科 来源:网络整理
导读:在C#中可以预先构建一个构造函数吗? 例如,考虑代码: public class A{ public bool ready = true; public A() { ready = false; // Point #1 // Other initialization stuff ready = true; // Point #2 }} 在代码的其他地方,两个线程可以访问类型A的变量,第
在C#中可以预先构建一个构造函数吗?

例如,考虑代码:

public class A
{
    public bool ready = true;

    public A()
    {
        ready = false; // Point #1
        // Other initialization stuff
        ready = true; // Point #2
    }
}

在代码的其他地方,两个线程可以访问类型A的变量,第一个线程调用在第1点被抢占的构造函数.然后第二个线程测试准备,并发现它仍然是真的,因此它做坏事.

这种情况是否可行?

进一步来说:

>可以预先构建一个构造函数吗?
>如果是这样,这是否意味着应该有同步代码,如锁在构造函数?
>构造函数退出之后,正在构造的对象是否只分配给共享变量,从而完全避免了这个问题?

解决方法

我不认为接受的答案是正确的. Igor Ostrovsky的“ The C# Memory Model in Theory and Practice”( part 2 here)彻底解释了这些问题,其中一个例子说明了你正在问的问题.

它给出代码

class BoxedInt2
{
  public readonly int _value = 42;
  void PrintValue()
  {
    Console.WriteLine(_value);
  }
}

class Tester
{
  BoxedInt2 _box = null;
  public void Set() {
    _box = new BoxedInt2();
  }
  public void Print() {
    var b = _box;
    if (b != null) b.PrintValue();
  }
}

并注意:

Because the BoxedInt instance was incorrectly published (through a non-volatile field,_box),the thread that calls Print may observe a partially constructed object! Again,making the _box field volatile would fix the issue.

我强烈地鼓励阅读整篇文章,这是非常有用的阅读.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读