在致電Interlocked.Increment
之後,檢查溢出的正確方法是什麼?如何在C#中的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
就會溢出,我想拋出一個excetption在這種情況下(崩潰儘早調試)。從Microsoft's documentation
摘錄:
該方法通過包裝處理溢出狀況:如果
location
=Int32.MaxValue
,location + 1
=Int32.MinValue
。沒有例外被拋出。
建議使用'long'
請注意'(uint)int.MinValue'拋出。 – SLaks
@SLaks(你最近的評論)那麼,作爲一個文字的'(uint)int.MinValue'將不會被編譯。但是一個非const的變量或者表達式'int i = int.MinValue'會影響轉換'(uint)i''不會拋出通常的'unchecked'上下文。 –