【问题标题】:What is the correct way to get the next value in every thread?在每个线程中获取下一个值的正确方法是什么?
【发布时间】:2023-04-11 12:11:01
【问题描述】:

我有一个多线程场景,我使用了 1000 个线程:

private ConcurrentDictionary<TableNames, int> _lastInsertedIds = new ConcurrentDictionary<TableNames, int>();

Parallel.For(0, 100, i => {
  var id = ++_lastInsertedIds[TableNames.Scores];
});

无论执行顺序如何,如何确保 id 始终是次高的?

我想避免使用手动锁定对象。

【问题讨论】:

    标签: c# multithreading locking concurrentdictionary


    【解决方案1】:

    你可以使用AddOrUpdate:

    Parallel.For(0, 100, i => {
      var id = _lastInsertedIds.AddOrUpdate(TableNames.Scores, 1, (key, existing) => existing + 1);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多