Thread safe way to change the value of int

In C#, if you want to change the value of an int and be thread safe, you can do it easily with the code below:
int oldInt = 20;
int newInt = 50;
Interlocked.Exchange(ref oldInt, newInt);

Msdn says: Interlocked Class provides atomic operations for variables that are shared by multiple threads.
And it’s not just limited to int, you can do it with all the basic types, float, double, short, long, etc. And even with object, since object is just a reference represented by a memory address internally.

Leave a Reply