I've read Task.Run with Parameter(s)? Follow the ways suggested in some answers, I'll have the following issue.
var tasks = new List<Task>();
for (int i = 0; i < 10; i++)
tasks.Add(Task.Run(() => Console.WriteLine(i)));
Task.WaitAll(tasks.ToArray());
Normally I would expected it passes the values of i
from 0 to 9 to the lambda in the Task.Run()
each time. Turned out the actual values passed in really depend, but most likely it just creates all the 10 tasks and then runs them, so what prints out is just all 10
s like: 10, 10, 10, 10, 10, 10, 10, 10, 10, 10. Or sometimes it's: 3, 3, 3, 10, 10, 10, 10, 10, 10, 10.
So how can I solve this nicely? Or in this situation, have to use Task.Factory.StartNew()
?