Task.Run with Parameter(s)?

后端 未结 7 1981
生来不讨喜
生来不讨喜 2020-12-02 10:45

I\'m working on a multi-tasking network project and I\'m new on Threading.Tasks. I implemented a simple Task.Factory.StartNew() and I wonder how ca

7条回答
  •  难免孤独
    2020-12-02 11:29

    It's unclear if the original problem was the same problem I had: wanting to max CPU threads on computation inside a loop while preserving the iterator's value and keeping inline to avoid passing a ton of variables to a worker function.

    for (int i = 0; i < 300; i++)
    {
        Task.Run(() => {
            var x = ComputeStuff(datavector, i); // value of i was incorrect
            var y = ComputeMoreStuff(x);
            // ...
        });
    }
    

    I got this to work by changing the outer iterator and localizing its value with a gate.

    for (int ii = 0; ii < 300; ii++)
    {
        System.Threading.CountdownEvent handoff = new System.Threading.CountdownEvent(1);
        Task.Run(() => {
            int i = ii;
            handoff.Signal();
    
            var x = ComputeStuff(datavector, i);
            var y = ComputeMoreStuff(x);
            // ...
    
        });
        handoff.Wait();
    }
    

提交回复
热议问题