Am I right in thinking this is the correct use of a Concurrent Dictionary

private ConcurrentDictionary<int,long> myDic = new ConcurrentDictionary<int,long>();

//Main thread at program startup

for(int i = 0; i < 4; i++)
{
  myDic.Add(i, 0);
}

//Separate threads use this to update a value

myDic[InputID] = newLongValue;

I have no locks etc and am just updating the value in the dictionary even though multiple threads might be trying to do the same.

推荐答案

It depends on what you mean by thread-safe.

From MSDN - How to: Add and Remove Items from a ConcurrentDictionary:

ConcurrentDictionary<TKey, TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

So, it is possible to get an inconsistent view of the value of an item in the dictionary.

.net相关问答推荐

.NET 7.0中的UseHttpsRedirection和IIS生产部署

Ubuntu 22.04 + JetBrains Rider 不能做脚手架 dbContext

无法实例化类的代理:System.Net.HttpWebRequest.找不到无参数构造函数

标签从右向左增长

如何在任务栏顶部全屏显示 Windows 窗体?

不同命名空间中的部分类

如何在 C# 中直接执行 SQL 查询?

如果需要,将方案添加到 URL

新的 netstandardapp 和 netcoreapp TFM 有什么区别?

形成两个列表并集的最简单方法

如何对 LINQ to XML 中的元素进行深层复制?

C# - 你如何停止计时器?

如何从 .NET 读取 PEM RSA 私钥

List 是否保证项目将按照添加的顺序返回?

找不到库 hostpolicy.dll

如何将 .NET 应用程序编译为本机代码?

WPF 中的 Application.DoEvents() 在哪里?

在 C#/.NET 中合并两个图像

在 .NET 中乘以时间跨度

什么时候使用 Tuple 和 KeyValuePair 比较好?