List.Add() thread safety

后端 未结 9 2302
庸人自扰
庸人自扰 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:43

    I solved my problem using ConcurrentBag instead of List like this:

    ConcurrentBag list = new ConcurrentBag();
    Parallel.ForEach(transactions, tran =>
    {
        list.Add(new object());
    });
    
        

    提交回复
    热议问题