Do i need a lock on a list? C#

喜欢而已 提交于 2020-01-14 12:48:28

问题


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-

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


回答1:


If you're not modifying the collection, you won't need locking at all.

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

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.




回答2:


If you're absolutely sure you are not modifying the actual lists (adding items, removing items, etc) you don't need a lock.




回答3:


You don't need a lock if you don't write. However if you are writting in the other threads then you should have a lock. Even if those threads only access specific ranges, if you add nodes to the list that can cause problems. If you are not altering the list structure but only changing whatever its in the nodes then I don't think there is a problem.




回答4:


In your struct object, I would at least mark the variable as ReadOnly and maybe the new ReadOnlyCollection

public struct MyStruct
{
    private readonly ReadOnlyCollection<int> _myInts;

    public MyStruct(ReadOnlyCollection<int> ints)
    {
        _myInts = ints;
    }
}



回答5:


Have you considered using arrays? An array is thread-safe as long as you don't access the same index in two threads. Also, it is quicker if you don't change the size.



来源:https://stackoverflow.com/questions/788674/do-i-need-a-lock-on-a-list-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!