t2.Tick += (o, v) => { for (int i = 0; i < list.Count; i++) { if (i >= 397) continue;// для проверки new Thread(() => { list[i].ping(t2.Interval); }).Start(); dvg[4, list[i].numPrint].Value = list[i].ipStatus; } }; 

list.Count = 397. When i = 397, it enters a loop, creates a thread. Why is the condition ignored? prompt knowing. Thank you in advance.

  • Closures capture variables, not their values. - PetSerAl
  • Ie i = 397 when creating a thread because at the moment of time when the thread is created, has it already been increased? I understood correctly? - Vitaly Shebanits

1 answer 1

That's right. In your code

 for (int i = 0; i < list.Count; i++) { if (i >= 397) continue;// для проверки new Thread(() => { list[i].ping(t2.Interval); }).Start(); dvg[4, list[i].numPrint].Value = list[i].ipStatus; } 

The stream does not start instantly, so by the time the stream starts, variable i has already been increased. If you need to capture the value of the variable i , you can first copy it to another local variable, for example

 for (int i = 0; i < list.Count; i++) { if (i >= 397) continue;// для проверки var j=i; // копия new Thread(() => { list[j].ping(t2.Interval); }).Start(); // захват копии переменной dvg[4, list[i].numPrint].Value = list[i].ipStatus; } 
  • I think the copy is stupid, it is easier to operate with a variable from only one thread, and then it will not increase its value. Thanks anyway. - Vitaliy Shebanits
  • one
    @ VitaliyShebanits I did not understand anything - Igor
  • one
    @ VitaliyShebanits except "thank you" - Igor