列表是否可以被多个线程访问? [英] Can a List<t> be accessed by multiple threads?

查看:83
本文介绍了列表是否可以被多个线程访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算在多个线程之间共享一个列表.该列表在更改期间会被锁定,这种更改很少发生.如果同时从列表中的不同线程进行多次迭代,是否存在线程安全问题?

I am planning to share a List between multiple threads. The list will be locked during a changes, which happen infrequently. Is there a thread safety issue if multiple iterations are made from different threads through the list simultaneously?

推荐答案

如果可以(如果可以使用.NET 4),请使用

If you can (if you can use .NET 4 that is), use BlockingCollection<T>:

为实现IProducerConsumerCollection<T>的线程安全集合提供阻止和绑定功能.

Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>.

如果没有,则完全封装该列表,并添加访问List<T>'s状态的线程安全方法.不要公开引用该列表,也不要通过任何方法返回该列表-始终封装该引用,以确保可以锁定对它的所有访问.

If not then encapsulate the list completely and add thread-safe methods that access the List<T>'s state. Don't make the reference to the list public or return it from any methods - always encapsulate the reference so you can guarantee that you are locking around all access to it.

这篇关于列表是否可以被多个线程访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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