簡體   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