繁体   English   中英

在每个线程中获取下一个值的正确方法是什么?

[英]What is the correct way to get the next value in every thread?

我有一个多线程场景,我调整了1000个线程:

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

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

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

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

您可以使用AddOrUpdate

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM