是ReadOnlyCollection还线程如果底层集合不会感动? [英] Is ReadOnlyCollection threadsafe if the underlying collection is not touched?

查看:111
本文介绍了是ReadOnlyCollection还线程如果底层集合不会感动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN 中隐约提到:

  

一个ReadOnlyCollection还≤(中≤(T>)>)可以同时支持多个阅读,只要集合不会被改动。 即便如此,通过集合进行枚举本质上并不是一个线程安全的过程。若要确保枚举过程中的线程安全,可以在整个枚举过程中锁定集合。要允许多个线程读取和写入访问的集合,您必须实现自己的同步。

请问下列公共静态集合是安全的多线程遍历?如果没有,是否有东西内置到.NET是安全的?如果我只是删除 ReadOnlyCollection还并为SomeStrings属性的getter的每次访问创建一个私人收藏的新副本?据我所知,有可能是一个死锁问题,如果多个线程试图对公众收集锁定,但是这是一个内部库,我看不出为什么我们会永远想。

 公共静态类WellKnownStrings {

    公共静态只读的ICollection<字符串> SomeStrings;

    静态WellKnownStrings()
    {
        收藏<字符串> someStrings =新的集合<字符串>();
        someStrings.Add(字符串1);
        someStrings.Add(字符串2);
        SomeStrings =新ReadOnlyCollection还<字符串>(someStrings);
    }
}
 

解决方案

一般情况下,永远不会改变其内部状态(一次发布到外来电)不可变对象可以被看作是线程安全的。

A ReadOnlyCollection还< T> 然而,是不是线程安全的本身,因为它是围绕现有集合其拥有者可以修改任何时候只有包装

在OP的例子是线程安全的,但因为基础集合不能被修改(至少在没有黑客)。

MSDN vaguely mentions:

A ReadOnlyCollection<(Of <(T>)>) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can 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.

Would the following public static collection be safe for multiple threads to iterate over? If not, is there something built into .NET that is safe? Should I just drop the ReadOnlyCollection and create a new copy of a private collection for each access of a SomeStrings property getter? I understand that there could be a deadlock issue if multiple threads tried to lock on the public collection, but this is an internal library, and I can't see why we would ever want to.

public static class WellKnownStrings {

    public static readonly ICollection<string> SomeStrings;

    static WellKnownStrings()
    {
        Collection<string> someStrings = new Collection<string>();
        someStrings.Add("string1");
        someStrings.Add("string2");
        SomeStrings = new ReadOnlyCollection<string>(someStrings);
    }
}

解决方案

Generally, an immutable object that never changes its internal state (once published to callers outside) can be seen as thread-safe.

A ReadOnlyCollection<T> however is not thread-safe per se, as it is a mere wrapper around an existing collection which its owner could modify any time.

The example in the OP is thread-safe though, because the underlying collection can't be modified (at least not without hacking).

这篇关于是ReadOnlyCollection还线程如果底层集合不会感动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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