On docs.microsoft.com says:
Note that although collisions are very rare, task identifiers are not guaranteed to be unique.
Does this mean that there can be tasks with the same IDs in the heap at the same time? Or does it mean that it can't be, but there are tasks with IDs that other tasks already had that no longer exist?
CodePudding user response:
It means that if you create 4,294,967,295 tasks, and read the Id
property of each one of them, the first and the last task will both have the value 1 as Id
.
You can see the source code of the Task.Id
property here. Below is the essence of this code:
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;
}
}