我正在查看.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/