首页 > 解决方案 > 如何以线程安全的方式生成顺序唯一 ID

问题描述

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

标签: c#multithreading

解决方案


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

public class Person
{
    private static int _counter;

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

推荐阅读