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

前端 未结 3 566
不知归路
不知归路 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:02

    You can use the locking block like the following code to insert items into your list in a thread-safe manner.

    var sync = new object();
    var myNewList = new List();
    Parallel.ForEach(myListOfSomethings, a =>
        {
            // Some other code...
            var someObj = new SomeObject();
            // More other code...
            lock(sync)
            {
                myNewList.Add(someObj);
            }
            // Even more code...
        });
    

提交回复
热议问题