c# - 如何以线程安全的方式生成顺序唯一 ID
问题描述
我已经调用了多个线程来生成一个数字,但我想为所有线程生成一个唯一的 no,(假设一个线程生成一个 no,即 ABC1 但第二个线程必须生成 ABC2 等等)
解决方案
您可以使用Interlocked.Increment
,这将在计数器上完成线程安全增量。
public class Person
{
private static int _counter;
public string GetNewId()
{
int id = Interlocked.Increment(ref _counter);
return $"ABC{id}";
}
}
推荐阅读
- c++ - 如何修复:for 循环不读取向量
- python - Alamofire 5(Beta 6):PUT 请求的参数未到达 Flask-Restful
- python - 无法在 web-scraper 的类方法中使用会话
- javascript - amp-form verify-xhr 似乎无法正常工作
- javascript - 在正文中的脚本执行之前加载一个外部 js 文件(没有 jQuery)
- python - Kivy - 矩形延迟绑定到图像
- java - Spring:密码加密
- tensorflow - 张量流嵌入中单词之间的距离
- python - 如何创建具有一个索引键列和多个值列的字典
- python-3.6 - 我试图制作一个excel表,但它似乎不起作用