I’m writing a multi threaded application, where one part of the code must be thread safe to keep track of task numbers.
I have this method:
private void IncrementTaskNumber() {
Interlocked.Increment(ref _TaskNumber);
}
_TaskNumber is a private int in the same class. The problem is, this throws me a “A property, indexer or dynamic member access may not be passed as an out or ref parameter” exception.
To get around this, I do:
private void IncrementTaskNumber() {
int _taskNum = _TaskNumber;
Interlocked.Increment(ref _taskNum);
_TaskNumber = _taskNum;
}
Is this still thread safe?
_TaskNumberhas to be a private field for this to work. You likely have it as a private property.Define it as:
And it will work.
Also note that your current workaround introduces a race condition – you’re effectively getting rid of the atomic increment by doing it using a temporary variable, which defeats the purpose of using
Interlockedin the first place. You need to increment the field directly.