I understand the functionality of Interlocked.Increment and lock(). But I'm confused on when to use one or the other. As far as I can tell Interlocked.Increment increments shared int/long value, whereas as lock() is meant to lock region of code.
For example, if i want to update string value it is possible with lock():
lock(_object)
{
sharedString = "Hi";
}
However, this is not possible with Interlocked class.
- Why can't this be done via
Interlocked? - What's the difference between these synchronization mechanisms?
Interlocked.Incrementcan and should be used to increment sharedintvariable. Functionally usingInterlocked.Incrementis same as:but
Interlocked.Incrementis much cheaper performance-wise.