【发布时间】:2021-11-06 08:01:50
【问题描述】:
我正在尝试生成可以从多个线程中使用的唯一 integer Id。
public partial class Form1 : Form
{
private static int sharedInteger;
...
private static int ModifySharedIntegerSingleTime()
{
int unique = Interlocked.Increment(ref sharedInteger);
return unique;
}
SimulateBackTestRow1()
{
while (true)
{
int num = ModifySharedIntegerSingleTime();
}
}
SimulateBackTestRow2()
{
while (true)
{
int num = ModifySharedIntegerSingleTime();
}
}
Task modifyTaskOne = Task.Run(() => SimulateBackTestRow1());
Task modifyTaskTwo = Task.Run(() => SimulateBackTestRow2());
但是,当采用以前未使用过的唯一编号的代码通过ModifySharedIntegerSingleTime 获取的编号时,我会遇到与非唯一编号发生冲突。
以thread-safe 方式获取唯一 int Id 的正确方法是什么?
【问题讨论】:
-
我很难相信——这意味着
Interlocked.Increment坏了
标签: c# multithreading task-parallel-library interlocked