I create one handler per channel in a loop: for (int i = 0; i < 4; i++) { actions.Add(() => Console.WriteLine(i)); }. Invoking the four actions afterwards prints 4 four times instead of 0, 1, 2, 3. The same happens when I start tasks in the loop with Task.Run(() => ReadChannel(i)): sometimes a channel is read twice, and ReadChannel(4) throws an out-of-range exception.
Oddly, the equivalent foreach loop prints the expected values. Why do the two loops behave differently, and what is the correct pattern?




