简体   繁体   English

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

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

I have a multi-threaded scenario, I spool up 1000 threads: 我有一个多线程场景,我调整了1000个线程:

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

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

How can I ensure the id is always the next highest no matter what the order of execution? 无论执行顺序如何,我如何确保id始终是最高的?

I would like to avoid using a manual lock object. 我想避免使用手动锁定对象。

You can use AddOrUpdate : 您可以使用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