Stopbyte

How to change variable value atomically in C# without locking thread?

i am working in an advanced multi threaded application, in which i need to change some variable values atomically. what i did so far is this:

private object _lock = new object();
 
public void ChangeValueAtomically(int a, int b, int comparingValue)
{
    if (a == comparingValue)
    {
        lock (_lock)
        {
            if (a == comparingValue)
            {
                a = b;
            }
        }
    }
}

But it’s causing my code to be so slow, as i need to do so many value changing atomically on a long list of listbox items in WPF.

is there any faster way to change variable values atomically, taking in consideration the value comparison?

I believe the method you are looking for isInterlocked.CompareExhange(). you can do it this way:

System.Threading.Interlocked.CompareExchange(ref a, b, comparingValue);

That function above, compares two values, if are equal it replaces the first variable “a” with the value of “b”.

For more information read these resources:

2 Likes

the shortest way to replace a variable value atomically is using:

System.Threading.Interlocked.CompareExchange(ref a, b, comparingValue);
1 Like

thanks Guys that’s exactly what I needed :slight_smile: @jms @afree