同步收集线程安全 [英] synchronized collection thread safety

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

问题描述

我有System.Collections.Generic.SynchronizedCollection共享集合。我们的代码使用.Net 4.0任务库来跨越线程,并将同步的集合传递到线程。到目前为止,线程尚未向集合中添加或删除项目。但是需要一个线程的新需求必须从集合中删除项目,而另一个线程只读取集合。在从集合中删除项目之前,我需要添加锁定吗?如果是这样,读者线程会线程安全吗?

I have System.Collections.Generic.SynchronizedCollection shared collection. Our code uses .Net 4.0 Task library to span threads and pass the synchronized collection to the thread. So far threads has not been adding or removing items into the collection. But the new requirement which requires one of the thread has to remove items from the collection while the other thread just read the collection. Do I need to add lock before removing the items from the Collection? If so, would reader thread be thread safe? Or Suggest best way to get the thread safety?

推荐答案

是的,SynchronizedCollection会为你锁定。

Yes, SynchronizedCollection will do the locking for you.

如果您有多个读者并且只有一个作者,您可能想使用ReaderWriterLock而不是SynchronizedCollection。

If you have multiple readers and just one writer, you may want to look at using a ReaderWriterLock, instead of SynchronizedCollection.

此外,如果您是.Net 4+,那么请查看 System.Collections.Concurrent 。这些类的性能比SynchronizedCollection好得多。

Also, if you are .Net 4+ then take a look at System.Collections.Concurrent. These classes have much better performance than SynchronizedCollection.

这篇关于同步收集线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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