如何以线程安全的方式生成顺序唯一 ID

San*_*ore 3 c# multithreading

我已经调用了多个线程来生成一个数字,但我想为所有线程生成一个唯一的 no,(假设一个线程生成一个 no,即 ABC1 但第二个线程必须生成 ABC2 等等)

Eva*_*oli 6

您可以使用Interlocked.Increment,这将在计数器上完成线程安全增量。

public class Person
{
    private static int _counter;

    public string GetNewId()
    {
        int id = Interlocked.Increment(ref _counter);
        return $"ABC{id}";
    }
}
Run Code Online (Sandbox Code Playgroud)


ric*_*hej 0

如果您只是想要一种线程安全的方式来生成唯一的数字,那么您可以执行以下操作:

private static object _lock = new object();
private static int mIdx = 0;
public static string GenerateNumber()
{
     lock (_lock)
     {
          return $"ABC{mIdx++}";
     }
}
Run Code Online (Sandbox Code Playgroud)