Saliya Ekanayake
Saliya Ekanayake

Reputation: 387

Is C# += thread safe?

Just ran into a program where += is used on a shared variable among threads, so is += thread safe, i.e. performs addition and assignment atomically?

Upvotes: 9

Views: 1880

Answers (4)

Saliya Ekanayake
Saliya Ekanayake

Reputation: 387

Thank you all for the quick replies. Yes, += is not thread safe and to verify this one may run the following simple program.

int count = 0;

        Parallel.For(0, 10000, i =>
        {
            count +=1; // not thread safe
        });
        Console.WriteLine(count);

Upvotes: 0

Sam Leach
Sam Leach

Reputation: 12956

string s += "foo";

is

string s = s + "foo";

s is read and then re-assigned. If in between these two actions the value of s is changed by another thread, the result with be different, so it's not thread safe.

Upvotes: 1

Mike Goodwin
Mike Goodwin

Reputation: 8880

You want

System.Threading.Interlocked.Add()

Upvotes: 2

Lee
Lee

Reputation: 144136

No it isn't thread safe since it's equivalent to:

int temp = orig + value;
orig = temp;

You can use Interlocked.Add instead:

Interlocked.Add(ref orig, value);

Upvotes: 12

Related Questions