List.Add() thread safety

后端 未结 9 2262
庸人自扰
庸人自扰 2020-11-29 07:57

I understand that in general a List is not thread safe, however is there anything wrong with simply adding items into a list if the threads never perform any other operation

9条回答
  •  抹茶落季
    2020-11-29 08:16

    If you want to use List.add from multiple threads and do not care about the ordering, then you probably do not need the indexing ability of a List anyway, and should use some of the available concurrent collections instead.

    If you ignore this advice and only do add, you could make add thread safe but in unpredictable order like this:

    private Object someListLock = new Object(); // only once
    
    ...
    
    lock (someListLock)
    {
        someList.Add(item);
    }
    

    If you accept this unpredictable ordering, chances are that you as mentioned earlier do not need a collection that can do indexing as in someList[i].

提交回复
热议问题