c# - 如何在 C# 中检查 Interlocked.Increment 后是否溢出?

标签 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;
    }
}

考虑到我每次运行生成的 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/

相关文章:

deadlock - Interlocked.CompareExchange <T>是否已废弃C# “lock”构造?

c# - CS8625 无法将空文字转换为 Interlocked.Exchange(ref c, null) 的不可空引用类型警告

c++ - InterlockedExchange 和内存可见性

c# - 以编程方式在 c# 中添加 [XmlIgnore] 属性以进行序列化

c# - 如何获取RadTreeView的点击节点文本

c# - mongoDB 的问题。类型的属性 '_id' ... 不能使用元素名称 '_id'

c - 了解 `int` 和 `long long` 变量的整数溢出

c# - 在 XAML 中使用静态函数绑定(bind)

c - 为什么 -0x80000000 + -0x80000000 == 0?

c - 减去指针 p - (p - 1) 如何造成整数溢出?