线程安全的List< T>属性 [英] Thread-safe List<T> property

查看:154
本文介绍了线程安全的List< T>属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要的实施列表< T> 作为可以线程安全地使用没有任何怀疑的属性。

I want an implementation of List<T> as a property which can be used thread-safely without any doubt.

事情是这样的:

private List<T> _list;

private List<T> MyT
{
    get { // return a copy of _list; }
    set { _list = value; }
}

看来我还是需要返回集合的副本(克隆),所以如果某个地方,我们遍历集合和集合设置在同一时间,则不会引发异常。

It seems still I need to return a copy (cloned) of collection so if somewhere we are iterating the collection and at the same time the collection is set, then no exception is raised.

如何实现一个线程安全的集合属性?

How to implement a thread-safe collection property?

推荐答案

如果您正在打靶的.Net 4中有<一个几个选项href=\"http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx\">System.Collections.Concurrent命名空间

If you are targetting .Net 4 there are a few options in System.Collections.Concurrent Namespace

您可以使用 ConcurrentBag&LT; T&GT; 在这种情况下,而不是列表&LT; T&GT;

You could use ConcurrentBag<T> in this case instead of List<T>

这篇关于线程安全的List&LT; T&GT;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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