c# - msft为什么将Interlocked.Increment(ref uniqueId)与零进行比较?

标签 c# multithreading task-parallel-library

我正在查看.NET 4.0的System.Threading.Tasks.TaskScheduler.Id实现,请参见以下代码:

[__DynamicallyInvokable]
public int Id
{
    [__DynamicallyInvokable]
    get
    {
        if (this.m_taskSchedulerId == 0)
        {
            int num = 0;
            do
            {
                num = Interlocked.Increment(ref s_taskSchedulerIdCounter);
            }
            while (num == 0);
            Interlocked.CompareExchange(ref this.m_taskSchedulerId, num, 0);
        }
        return this.m_taskSchedulerId;
    }
}

为什么互锁后msft比较num == 0? Interlocked.Increment()的实现说它返回递增后的值(递增后),因此检查零似乎是不必要的(除非计数器回绕,但是如果发生这种情况,您还有更大的问题,在这里也无法解决。

如果要这样做,我只会做:
public int Id
        {
            get
            {
                if(m_taskSchedulerId==0)
                {
                    var result = Interlocked.Increment(ref s_taskSchedulerIdCounter);
                    Interlocked.CompareExchange(ref m_taskSchedulerId, result, 0);
                }
                return m_taskSchedulerId;
            }
        }

最佳答案

but if that happens you have bigger problems



不,这就是他们这样做的确切原因。从Reference Source:
public Int32 Id
{
    get
    {
        if (m_taskSchedulerId == 0)
        {
            int newId = 0;

            // We need to repeat if Interlocked.Increment wraps around and returns 0.
            // Otherwise next time this scheduler's Id is queried it will get a new value
            do
            {
                newId = Interlocked.Increment(ref s_taskSchedulerIdCounter);
            } while (newId == 0);

            Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0);
        }

        return m_taskSchedulerId;
    }
}

关于c# - msft为什么将Interlocked.Increment(ref uniqueId)与零进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12635009/

相关文章:

c# - C#中的多线程和多任务处理之间的区别

java - 为什么所有 Future.get() 在 invokeAll 中都会抛出 CancelleationException 并超时

c# - 任务中的秒表似乎在所有任务中都是可加的,只想测量任务间隔

c# - 我使用 IO 的所有操作都应该是异步的吗?

c# - 具有取消能力的长时间运行操作模式

c# - XAML:更改 DataContext 时更新绑定(bind)

c# - 在非托管 C++ 项目中使用 C# COM -> 0x7697C41F (KernelBase.dll) 处的第一次异常

c# - Xamarin.Forms:订阅事件处理程序 VS。指挥

C# If Else 语句选择合适的 Xpath 表达式

multithreading - 对与 unique_lock 关联的互斥体调用解锁会导致未定义的行为