C# 结构线程安全吗? [英] Are C# structs thread safe?

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

问题描述

C# struct 是线程安全的吗?

Is a C# struct thread-safe?

例如如果有:

struct Data
{
    int _number;
    public int Number { get { return _number; } set { _number = value; } }

    public Data(int number) { _number = number; }
}

另一种:

class DadData
{
    public Data TheData { get; set; }
}

名为 TheData 的属性是否是线程安全的?

is property named TheData, thread-safe?

推荐答案

不,.NET 中的结构本质上不是线程安全的.

No, structures in .NET are not intrinsically thread-safe.

然而,结构体的逐值复制语义与这种转换有很大关系.

However, the copy-by-value semantics that structures have great relevance to this converation.

如果您要传递结构并以某种方式将它们分配给变量或按值传递参数(没有 ref 或 out 关键字),则正在使用 copy.

If you are passing your structures around and assigning them in some way to variables or pass-by-value parameters (no ref or out keywords) then a copy is being used.

当然,这意味着对副本所做的任何更改都不会反映在原始结构中,但在传递它们时需要注意.

Of course, this means that any changes made to the copy are not reflected in the original structure, but it's something to be aware of when passing them around.

如果您以不涉及按值复制语义的方式直接访问结构(例如访问作为结构类型的静态字段,并且作为 Marc Gravel 在他的回答中指出,还有很多其他方法)跨多个线程,那么你必须考虑考虑实例的线程安全.

If you are accessing the structure directly in a manner that doesn't involve copy-by-value semantics (e.g. accessing a static field which is the type of the structure, and as Marc Gravel points out in his answer, there are many other ways) across multiple threads, then you have to take into account the thread-safety of the instance.

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

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