我需要一个列表上的锁? C# [英] Do i need a lock on a list? C#

查看:142
本文介绍了我需要一个列表上的锁? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用默认值填充了几个列表<>,将它们粘贴到一个结构体中,然后将结构体传递到多个线程中。每个线程有不同的范围,所以线程1将访问列表[0到199]线程2将访问[200 - 400]等。我需要一个锁吗?和什么时候我需要它?我可以访问该列表与我的多个线程w / o使用锁。但是如果我的主线程想要读取列表中的数据(从不写),我需要一个锁吗?

I filled several list<> with default values, stuck them into a struct then pass the struct into several threads. Each thread has a different range so thread 1 would access list[0 to 199] thread 2 would access [200 - 400] etc. Would i need a lock? and when do i need it? i can access the list with my multiple threads w/o using a lock. But if my main thread wants to read the data in the list (never write) do i need a lock for that? i'm sure i dont but i would like to ask before implementation.

-edit -

-edit-

谢谢你们,你回答了我的问题。 (我会稍后接受一个人,只要有人不反对当前的答案)

Thanks guys, you answered my question. (I will accept one later as long as someone doesnt disprove current answers)

推荐答案

如果你不修改集合,

如果要使用其中一个线程修改集合,您可能需要查看ReaderWriterLock

If you want to modify the collection with one of the threads, you might want to look at the ReaderWriterLock.

彼得的评论是值得注意的中。正如上面的MSDN链接所指出的,您应该考虑使用 ReaderWriterLockSlim 类if你在.NET 3.5。这个想法是一样的。

Peter's comment is a notable one. As also noted by the MSDN link above, you should consider using ReaderWriterLockSlim class if you're on .NET 3.5. The idea is the same, nevertheless.

这篇关于我需要一个列表上的锁? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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