如果我预加载一个带有结构的字典并保证永远不会向它添加任何更多的项目,如果我从一个线程更新项目并从另一个线程读取它们是否是线程安全的。
struct DataItem
{
public double Price;
public double Size;
}
class Test
{
Dictionary<string, DataItem> items = new Dictionary<string,DataItem>(3);
public Test ()
{
items["A"] = new DataItem(){Price=100, Size=1000};
items["B"] = new DataItem(){Price=200, Size=2000};
items["C"] = new DataItem(){Price=300, Size=3000};
}
一个线程会调用这个方法
public void UpdateItem()
{
DataItem newItem = new DataItem(){Price=400, Size=4000};
items["A"] = newItem;
}
一个不同的线程会调用这个方法
public DataItem GetItem(string key)
{
return items[key];
}
}
最佳答案
A
Dictionary<TKey, TValue>
can support multiple readers concurrently, as long as the collection is not modified.
因此让读者和作者同时操作不是线程安全的。
关于c# - 如果不调整大小,C# 通用结构字典是否线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306418/