My understanding is that all the Interlocked
APIs in .NET will introduce a full memory fence. However, I still see many examples where volatile
, which introduces half-fences, is used in conjunction with Interlocked
. An example of that is Task.Id
:
https://source.dot.net/#System.Private.CoreLib/Task.cs,784864bc4dc294af
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;
}
}
In instances like this, what is volatile
actually doing?