如果我填充一个字典并将其分配给一个字段 - 我可以保证该字段不会包含一半填充的字典吗?

问题描述 投票:0回答:1

在下面的代码中,我填充字典的内容然后将其分配给

Data
。因此,我的心理预期是
Data
将包含
null
或包含两个元素的
Dictionary

但是这是一个有效的期望吗?

我知道写入可以重新排序。据推测,简单的修复方法是将

volatile
添加到
Data
。但这有必要吗?或者原始代码保证“安全”(安全是指我可以 100% 确信
Data
永远不会包含具有 < 2 elements in it).

的字典)
using System;
using System.Collections.Generic;

public class Program
{
    public static Dictionary<int, int> Data = null;
    
    public static void Main()
    {
        var bob = new Dictionary<int, int>();
        bob.Add(1, 1);
        bob.Add(2, 2);
        
        Data = bob;

        // Note that there be no further mutation of `bob` or `Data` after this.

        // Imagine there is a separate thread reading the contents of `Data`
    }
}
c# multithreading thread-safety volatile
1个回答
0
投票

我知道写入可以重新排序。据推测,简单的修复方法是将

volatile
添加到
Data
。但这有必要吗?

是的,绝对需要。如果没有

volatile
,编译器/抖动/处理器可能会 重新排序 程序的指令,使得
Data
可能会在短时间内指向部分初始化的
Dictionary<K,V>
对象。部分初始化的对象的行为是未定义的。它可能包含少于 2 个元素,它可能会抛出异常,等等。或者它可能会正常工作,因为实际上没有发生重新排序。如果你想负责任,不留一丝侥幸,你一定要把
Data
声明为
volatile
,这样就可以防止任何重新排序的可能性。

© www.soinside.com 2019 - 2024. All rights reserved.