Starting a new thread in a foreach loop

后端 未结 5 957
你的背包
你的背包 2020-12-05 10:24

I have a List of objects and I\'d like to loop over that list and start a new thread, passing in the current object.

I\'ve written an example of what I thought shoul

相关标签:
5条回答
  • 2020-12-05 10:58

    Agree with Reed's answer (+1).

    I would add that if you are on .NET 4, you may want to look at the Task Parallel Library to solve this class of problem. Specifically for this case, have a look at Parallel.ForEach().

    0 讨论(0)
  • 2020-12-05 11:03

    This is because you're closing over a variable in the wrong scope. The solution here is to use a temporary in your foreach loop:

        foreach(MyClass myObj in myList)
        {
            MyClass tmp = myObj; // Make temporary
            Thread myThread = new Thread(() => this.MyMethod(tmp));
            myThread.Start();
        }
    

    For details, I recommend reading Eric Lippert's post on this exact subject: Closing over the loop variable considered harmful

    0 讨论(0)
  • 2020-12-05 11:07

    The problem is that you are using the most current value of the object inside of your closure. So, each invocation of the thread is looking at the same value. To get around this, copy the value into a local variable:

    foreach(MyClass myObj in myList)
    {
        MyClass localCopy = myObj;
        Thread myThread = new Thread(() => this.MyMethod(localCopy));
        myThread.Start();
    }
    
    0 讨论(0)
  • 2020-12-05 11:08

    if sequence is not matter than go for

    Parallel.ForEach(myList, obj => this.MyMethod(obj) );
    

    Write a Simple Parallel.ForEach Loop

    0 讨论(0)
  • 2020-12-05 11:17

    I prefer this way:

    public void ThreadingMethod()
    {
        var myList = new List<MyClass> { new MyClass("test1"), new MyClass("test2") };
    
    
    Parallel.ForEach(myList, new ParallelOptions() { MaxDegreeOfParallelism = 100 },
             (myObj, i, j) =>
             {
                 MyMethod(myObj);
             });
    
    }
    

    not tested though....

    0 讨论(0)
提交回复
热议问题