Task.Run with Parameter(s)?

后端 未结 7 1958
生来不讨喜
生来不讨喜 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:28

    Idea is to avoid using a Signal like above. Pumping int values into a struct prevents those values from changing (in the struct). I had the following Problem: loop var i would change before DoSomething(i) was called (i was incremented at end of loop before ()=> DoSomething(i,ii) was called). With the structs it doesn't happen anymore. Nasty bug to find: DoSomething(i, ii) looks great, but never sure if it gets called each time with a different value for i (or just a 100 times with i=100), hence -> struct

    struct Job { public int P1; public int P2; }
    …
    for (int i = 0; i < 100; i++) {
        var job = new Job { P1 = i, P2 = i * i}; // structs immutable...
        Task.Run(() => DoSomething(job));
    }
    

提交回复
热议问题