如何正确从线程池访问ArrayList?
我在我的 c# 应用程序上使用 ThreadPool,并且需要从“全局”ArrayList 添加和删除项目。线程将随时访问相同的ArrayList
。我应该如何以安全的方式做到这一点?因此没有线程会同时尝试访问 ArrayList。
我用这个开始线程:
my_args args = new my_args(input, id, this);
ThreadPool.QueueUserWorkItem(new WaitCallback(generateKeywords), args);
I am using ThreadPool
on my c# application and I need to add and remove items from an "global" ArrayList
. The threads will be accessing the same ArrayList
at any time. How should I do this in a safe way? So no threads will try to access the ArrayList at the same time.
I am starting the threads with this:
my_args args = new my_args(input, id, this);
ThreadPool.QueueUserWorkItem(new WaitCallback(generateKeywords), args);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以围绕 ArrayList 创建一个线程安全的包装器:
但请注意,即使使用同步的 ArrayList,通过列表进行枚举仍然不安全。有关详细信息,请参阅此 msdn 页面。
我能问一下为什么使用
ArrayList
而不是通用集合吗?如果您使用该列表作为队列来提供几个工作进程,并且您使用的是 .net 4.0,则可以使用BlockingCollection
对象。有关详细信息,请参阅此 msdn 页面。You can create a thread safe wrapper around the
ArrayList
:Note however that even with a synchronized
ArrayList
it is still not safe to enumerate through the list. See this msdn page for more information.Can I ask why you use an
ArrayList
instead of a generic collection? If you use the list as a queue to feed a couple of worker processes, and you are using .net 4.0, then you can use aBlockingCollection<T>
object. See this msdn page for more information.我会使用 SyncRoot 来锁定阵列。
I would use SyncRoot to lock the array.
您可以尝试使用 lock 语句将数组作为参数:
You may try to use lock statement with your array as argument:
如果您有 .NET 4 可用,更好的选择是使用 System.Collections.Concurrent。这些都提供线程安全的读写,无需显式锁定。
(其中一些集合是无锁的,一些使用细粒度锁定,但它们都是线程安全的,无需您担心。)
A better option, if you have .NET 4 available, would be to use one of the collections in System.Collections.Concurrent. These all provide thread safe reading and writing without explicitly locking.
(Some of these collections are lock free, some use fine grained locking, but they are all thread safe, without you having to worry about it.)