Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 555
Saliya Ekanayake Avatar asked Oct 11 '13 20:10

Saliya Ekanayake


3 Answers

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);
like image 143
Lee Avatar answered Nov 20 '22 13:11

Lee


You want

System.Threading.Interlocked.Add()
like image 32
Mike Goodwin Avatar answered Nov 20 '22 12:11

Mike Goodwin


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.

like image 1
Sam Leach Avatar answered Nov 20 '22 12:11

Sam Leach