I am trying to understand Interlocked in C# in thread synchronization.
public int MethodUsedByMultipleThreads()
{
var id = CreateNextId();
return id;
}
private long CreateNextId()
{
long id = 0;
Interlocked.Exchange(ref id , this._nextId);
Interlocked.Increment(ref this._nextId);
return id;
}
Is the line
Interlocked.Exchange(ref id , this._nextId);
redundant if I directly use
Interlocked.Increment(ref this._nextId);
return _nextId;
Will it serve the same purpose?
The line
is both redundant and incorrect. It is redundant because it is practically the same as:
...because the
idis a local variable that is not shared with other threads. And it is incorrect because there is a race condition between incrementing the_nextIdfield and returning it from the methodCreateNextId(). The correct implementation is:...or simply:
The method
Interlocked.Incrementincrements the_nextIdfield, and returns the incremented value as an atomic operation.The subtraction
- 1is there to preserve the semantics of your existing code, regarding the meaning of the field_nextId. It might be preferable to change its name to_lastIdor_idSeed, so that the- 1can be removed.