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

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

问题描述

是一个C#结构线程安全的?

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; }
}

在属性命名海图,线程安全的?

is property named TheData, thread-safe?

推荐答案

没有,结构.NET本质上并没有线程安全的。

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

然而,复制值语义的结构有很大的关联这个converation。

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

如果你身边路过的结构和以某种方式变量或传递by-value参数(没有ref或out关键字)分配给它们那么的复制的正在使用。

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.

如果你正在直接访问结构的方式,不涉及拷贝按值的语义(例如,访问的静态字段,它是结构的类型,并作为马克碎石在他的回答,有多个线程很多其他的方法)所指出的,那么你必须考虑到占该实例的线程安全的。

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天全站免登陆