【发布时间】:2013-07-22 15:15:12
【问题描述】:
在调用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 在增加时可能会溢出(在异常大的输入上),我想在这种情况下抛出异常(早早崩溃到方便调试)。
此方法通过包装处理溢出条件:如果
location=Int32.MaxValue,location + 1=Int32.MinValue。不抛出异常。
【问题讨论】:
-
考虑使用
long。 -
请注意
(uint)int.MinValue抛出。 -
@SLaks(你的最后一条评论)好吧,
(uint)int.MinValue作为文字不会编译。但是一个非常量变量或表达式int i = int.MinValue命中转换(uint)i不会抛出通常的unchecked上下文。 -
@SLaks 谢谢,我没有想到,演员表应该用
unchecked包裹起来,像这样:unchecked((uint)int.MinValue)我想。
标签: c# integer-overflow interlocked interlocked-increment