C#+ =线程安全吗? [英] Is C# += thread safe?

查看:77
本文介绍了C#+ =线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需运行一个程序,在线程之间的共享变量上使用+ =,那么+ =线程安全吗,即原子地执行加法和赋值?

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?

推荐答案

不,它不是线程安全的,因为它等效于:

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

int temp = orig + value;
orig = temp;

您可以改用 Interlocked.Add :

You can use Interlocked.Add instead:

Interlocked.Add(ref orig, value);

这篇关于C#+ =线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆