Suz*_*ron 2 c# integer-overflow interlocked interlocked-increment
调用后检查溢出的正确方法是什么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;
}
}
Run Code Online (Sandbox Code Playgroud)
鉴于我每次运行生成的 ID 数量相当大,(在异常大的输入上)_counter增量时可能会溢出,并且我想在这种情况下抛出异常(尽早崩溃以简化调试)。
摘自微软的文档:
location此方法通过包装: if =Int32.MaxValue,location + 1=来处理溢出情况Int32.MinValue。没有抛出异常。
只需检查是否newId为Int32.MinValue(在转换为 之前uint)并抛出异常。
MinValue获得增量的唯一方法是通过溢出。