Destination Array not long enough?

后端 未结 4 1351
不知归路
不知归路 2020-12-08 13:07

I have a class with the following method:

public List bikesCopy 
{
     get 
     { 
       List bs;
       lock (_bikes) bs = new Li         


        
4条回答
  •  情书的邮戳
    2020-12-08 13:34

    This error occurs because multiple threads are adding items in a single list. Lists are by default not a thread-safe solution. In a multi-threaded code, it is only recommended to read from a list, and not write to it.

    As described here:

    If you are only reading from a shared collection, then you can use the classes in the System.Collections.Generic namespace.

    Better use a thread-safe solution like System.Collections.Concurrent namespace which provides implementations like ConcurrentBag, ConcurrentDictionary, ConcurrentQueue, ConcurrentStack etc.

    For example:

    public ConcurrentBag bikesCopy 
    {
         get => new ConcurrentBag()
    }
    

提交回复
热议问题