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

Jas*_*onS 1 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 8

但如果发生这种情况你会遇到更大的问题

不,这就是他们这样做的确切原因.来自参考资料来源:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)