.net - .NET CLR-对象引用同步

标签 .net multithreading thread-safety clr

在多线程.NET应用程序中,

假设第一个线程正在写入列表
第二个线程正在清除其中的所有项目。
第三线程正在从列表中读取。

如果第二个线程和第三个线程在CLR级别“真正”同时访问同一列表对象,会发生什么情况。我不是说.NET同步对象和锁定机制。

我的意思是,当CLR从引用(通过第3线程)访问列表项时,如果引用所指向的列表发生变化(通过第2线程)会怎样?

最佳答案

不好的东西。

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A List<T> can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

关于.net - .NET CLR-对象引用同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7123249/

相关文章:

c# - 编辑 WinForms RichTextBoxControl C#

c# - 编译器是否将处置的对象设置为空?

c# - 文本框填充

c# - 全局捕获后台线程中 WCF 异步调用引发的异常

java - Java TCP Server 中输入和输出的单独线程

c - 某些线程返回垃圾值?

ruby - 在(最新版本的)Ruby 中递增整数(使用 +=)线程安全吗?

c# - parallel.foreach 有效,但为什么呢?

c# - 循环序列中两个数字之间的距离

java - 对象在 Java 的构造函数中转义总是一个问题吗?