在调用 Interlocked.Increment
后检查溢出的正确方法是什么?
我有一个 ID 生成器,它在程序执行期间生成唯一的 ID,目前我测试增量是否返回零。
public static class IdGenerator {
private static int _counter = 0;
public static uint GetNewId() {
uint newId = (uint)System.Threading.Interlocked.Increment(ref _counter);
if (newId == 0) {
throw new System.Exception("Whoops, ran out of identifiers");
}
return newId;
}
}
考虑到我每次运行生成的 ID 数量相当大,_counter
有可能(在非常大的输入上)在递增时溢出,我想抛出一个异常案例(尽早崩溃以简化调试)。
摘自 Microsoft's documentation :
This method handles an overflow condition by wrapping: if
location
=Int32.MaxValue
,location + 1
=Int32.MinValue
. No exception is thrown.
最佳答案
只需检查 newId
是否为 Int32.MinValue
(在转换为 uint
之前)并抛出异常。
从增量中获取 MinValue
的唯一方法是通过溢出。
关于c# - 如何在 C# 中检查 Interlocked.Increment 后是否溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17791218/