Adding to a list in a Parallel.ForEach loop in a threadsafe manner

前端 未结 3 563
不知归路
不知归路 2020-12-06 01:28

I have a bit of code that works like this on a list of obj objects called ListofObjects:

List NewListofObjects();

Parall         


        
3条回答
  •  时光取名叫无心
    2020-12-06 02:14

    The .NET Framework 4 introduces the System.Collections.Concurrent namespace, which includes several collection classes that are both thread-safe and scalable. https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/

    BlockingCollection[] sourceArrays = new BlockingCollection[5];
    for (int i = 0; i < sourceArrays.Length; i++)
        sourceArrays[i] = new BlockingCollection(500);
    Parallel.For(0, sourceArrays.Length * 500, (j) =>
    {
        int k = BlockingCollection.TryAddToAny(sourceArrays, j);
        if (k >= 0)
            Console.WriteLine("added {0} to source data", j);
    });
    

提交回复
热议问题