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(); } } 并注意:
我强烈地鼓励阅读整篇文章,这是非常有用的阅读. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |