名单< T>同时删除和添加 [英] List<T> concurrent removing and adding

查看:148
本文介绍了名单< T>同时删除和添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也不太清楚,所以我想我会问。会删除和添加项目到 System.Collections.Generic.List<> 对象是非线程安全的。

I am not too sure, so i thought i'd ask. Would removing and adding items to a System.Collections.Generic.List<> object be non-thread safe?

我的情况:

当接收到一个连接,它被添加到列表中,而且在同一时间,有一个工人是真实除去死连接和这样

When a connection is received, it is added to the list, but also at the same time, there's a worker that's removing dead connections and such.

时有问题吗?将一个锁定吗? 我也想知道如果我允许的列表对象上使用的锁与它的的Foreach&LT;&GT; 方法

Is there a problem? Will a lock do? I also want to know if i'm allowed to use a lock on the list object with it's Foreach<> method.

推荐答案

是,添加和删除项名单,其中;&GT; 不是线程安全的,所以你需要使用同步访问,例如锁定

Yes, adding and removing items from a List<> is not thread safe, so you need to synchronise the access, for example using lock.

记住,在没有办法的锁定关键字锁定,你作为标识符使用对象,它只prevents两个线程进入同一个code座与此同时。您将身边需要锁的所有的code访问列表,使用的相同的对象的作为标识。

Mind that the lock keyword in no ways locks the object that you use as identifier, it only prevents two threads to enter the same code block at the same time. You will need locks around all code that accesses the list, using the same object as identifier.

这篇关于名单&LT; T&GT;同时删除和添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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