简体   繁体   中英

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

I have a multi-threaded scenario, I spool up 1000 threads:

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?

I would like to avoid using a manual lock object.

You can use AddOrUpdate :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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