Task.Id 属性 的非唯一性是什么意思?

What does the non-uniqueness of the Task.Id property mean?

docs.microsoft.com 上说:

Note that although collisions are very rare, task identifiers are not guaranteed to be unique.

这是否意味着堆中可以同时存在具有相同ID的任务?或者这是否意味着它不能,但是有其他任务已经拥有的 ID 不再存在的任务?

意思是如果你创建了4,294,967,295个任务,并且读取每个任务的Id 属性,那么第一个和最后一个任务的值都会是1,因为Id.

您可以查看Task.Id属性here的源代码。下面是这段代码的本质:

public class Task
{
    private volatile int m_taskId;

    public int Id
    {
        get
        {
            if (m_taskId == 0)
            {
                int newId = NewId();
                Interlocked.CompareExchange(ref m_taskId, newId, 0);
            }
            return m_taskId;
        }
    }

    internal static int s_taskIdCounter;

    internal static int NewId()
    {
        int newId = 0;
        do
        {
            newId = Interlocked.Increment(ref s_taskIdCounter);
        }
        while (newId == 0);
        return newId;
    }
}