是 C# 中的 bool 读/写原子 [英] Is a bool read/write atomic in C#

查看:26
本文介绍了是 C# 中的 bool 读/写原子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中访问 bool 字段是原子的吗?特别是,我是否需要加锁:

Is accessing a bool field atomic in C#? In particular, do I need to put a lock around:

class Foo
{
   private bool _bar;

   //... in some function on any thread (or many threads)
   _bar = true;

   //... same for a read
   if (_bar) { ... }
}

推荐答案

是.

以下数据类型的读写是原子的:bool、char、byte、sbyte、short、ushort、uint、int、float 和引用类型.

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.

C# 语言规范.

了解 volatile 关键字.

It's probably also worthwhile understanding the volatile keyword.

这篇关于是 C# 中的 bool 读/写原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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