哪些操作是原子在C#中?原子、操作

2023-09-02 11:47:37 作者:潇洒的微笑

有没有一种系统的方法来知道在C#中的操作是否是原子或没有?还是有经验的任何一般的指导原则或规则?

Is there a systematic way to know whether an operation in C# will be atomic or not? Or are there any general guidelines or rules of thumb?

推荐答案

对于一些更完整的/详细的:

For something more complete/detailed:

读取和写入的32位值类型的原子:这包括以下内在价值(结构)类型:布尔,字符,字节,为sbyte,短USHORT,UINT,浮动。以下几种类型(其中包括)不能保证是原子的:小数,双,长,ULONG

Reads and writes to 32-bit value types are atomic: This includes the following intrinsic value (struct) types: bool, char, byte, sbyte, short ushort, uint, float. the following types (amongst others) are not guaranteed to be atomic: decimal, double, long, ulong.

例如。

int x;
x = 10; // atomic
decimal d;

d = 10m; // not atomic

参考分配也是一个原子操作:

Reference assignment is also an atomic operation:

private String _text;
public void Method(String text)
{
  _text = text; // atomic
}