C#构造函数线程安全吗? [英] Is a C# Constructor thread safe?

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

问题描述

假设我有多个线程,并且每个线程都试图创建同一类的对象.
在不同线程中同时创建相同类型的对象是否会相互干扰? 我需要在构造函数中使用锁定"吗?

Let's say I have multiple threads and each of them is trying to create objects of the same class.
Will the simultaneous creation of objects of the same type in different threads interfere with each other? Do I need to use "lock" within the constructor?

推荐答案

这在很大程度上取决于构造函数的实现.

This depends very much on the implementation of the constructor.

如果构造函数仅访问该类的成员,而不访问任何外部静态类或方法,则可以-它是线程安全的.

If the constructor is only accessing members of that class, and not any external static classes or methods, then yes - it is thread safe.

但是,如果该构造函数正在访问存在于类本身之外的非线程安全对象(例如全局单例),则它不是线程安全的.

But if that constructor is accessing non-threadsafe objects that exist outside of the class itself, (such as a global singleton), then it is not threadsafe.

更新:构造函数应注意不要访问类的任何非只读或const静态成员. (感谢Nathan A和LVBen)

update: The constructor should be careful not to access any static members of the class that are not readonly or const. (thanks Nathan A and LVBen)

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

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