名单< T>同时删除和添加名单、LT、GT

由网友(野性入骨)分享简介:我也不太清楚,所以我想我会问。会删除和添加项目到 System.Collections.Generic.List<> 对象是非线程安全的。I am not too sure, so i thought i'd ask. Would removing and adding items to a System...

我也不太清楚,所以我想我会问。会删除和添加项目到 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.

阅读全文

相关推荐

最新文章