【问题标题】:Is += an atomic operation in C#? [duplicate]+= 是 C# 中的原子操作吗? [复制]
【发布时间】:2019-05-02 23:14:39
【问题描述】:

我在多线程环境下开发数据聚合对象,遇到以下情况:

int counts;

// This event is triggered by many threads at the same time
public void OnDataReceived(DataEvent evt)
{
   counts += evt.counts;
}

我的问题是这样做是否安全

counts += evt.counts;

或者我需要类似的东西

lock(lockObject)
{
   counts += evt.counts;
}

【问题讨论】:

  • += 不是 原子操作。您应该使用 Interlocked.Increment。
  • 不。顺便说一句,.NET 中的特定操作是否保证是原子的,不仅取决于操作本身,还取决于它应用到的数据类型...

标签: c# multithreading


【解决方案1】:

+= 不是原子操作。您应该使用Interlocked.Increment 方法。

【讨论】:

    猜你喜欢
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多