NET中不同的线程之间共享列表

NET中不同的线程之间共享列表

本文介绍了在.NET中不同的线程之间共享列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中的静态列表,将通过不同的线程访问,每一个加入,读,从列表中删除了自己独特的项目。我想知道有没有担心做这个变量的线程安全的,因为即使同一个列表对象线程之间共享,他们只能修改自己独特的项目

I have a static List in a class that will be accessed by different threads, each one adding, reading and removing its own unique item from the list. I would like to know if I have to worry about making this variable thread safe, as even though the same List object is shared between threads, they only modify their own unique items

推荐答案

您肯定要执行或者通过的或通过如ReaderWriterLockSlim.

You definitely have to implement thread-safe access either via lock or via e.g. ReaderWriterLockSlim.

变量本身(名单<>)是线程安全的,如果你不是第一次分配后修改它(通过新的),但元素访问必须是线程安全的(因为你说你添加/删除从列表中的元素,因此改变其状态)

Variable itself (List<>) is thread-safe if you not modifies it after first allocation (via new) but element access have to be thread-safe (since you say you adding/removing elements from list hence changing its state)

顺便说一句,如果线程修改了自己的项目,你为什么要分享?所以,你已经实现了?为什么组织这样?也许,如果你表现出的细节有更好的提醒。

BTW, if threads modifies its own items why you want to share them? So what you have implemented? Why you organize this way? Maybe there are better advise if you show details.

这篇关于在.NET中不同的线程之间共享列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:56