나는 .NET 4.0의 System.Threading.Tasks.TaskScheduler.Id 구현을보고, 다음 코드를 참조하고 있습니다 :msft에서 Interlocked.Increment (ref uniqueId)를 0으로 비교하는 이유는 무엇입니까?
[__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()의 구현은 증가 후 값을 반환하므로 0을 확인하는 것이 비현실적인 것으로 나타납니다 (카운터가 래핑되지 않는 한 그런 일이 발생하면 여기에서도 해결되지 않은 더 큰 문제가 있음)
내가 할 것 인 경우에, 나는 간단하게 할 거라고 :
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;
}
}
아마 "벨트 및 중괄호"접근 방식 일 수 있습니다. 반환 값이 어떤 식 으로든 0이면 다음에'Id '가 액세스 될 때'Id'가 다시 생성되고 (이번에는 0이 아닌 경우) -'Id'가 변경됩니다. –