如何将参数传递给匿名操作?我想我可以只使用匿名方法内部作用域中的值类型,它将复制它,但事实并非如此。那我该怎么办?
是的,我先尝试过google,但是我不确定要使用哪些搜索字词。
var Random = new Random();
List<Task> listOfTasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
listOfTasks.Add(Task.Run(() => {
var iterator = i;
var StopWatch = new Stopwatch();
StopWatch.Start();
Task.Delay(Random.Next(100, 15000)).Wait();
//Thread.Sleep(Random.Next(100, 15000));
StopWatch.Stop();
//** Why is i not passed in on creation of the anonymous method? All lines output 100, this makes me think i is not passes until they execute.
Console.WriteLine($"Task {iterator} Completed after {StopWatch.ElapsedMilliseconds} ms");
}
));
}
var Stopwatch = new Stopwatch();
Stopwatch.Start();
Console.WriteLine("All Tasks are Added");
Task.WaitAll(listOfTasks.ToArray());
Stopwatch.Stop();
Console.WriteLine($"Execution Time {Stopwatch.ElapsedMilliseconds} ms");
//** Usually around 48 seconds (Random is not really random, this I know), I would think this should be around 15 seconds since I am using Task.Delay and not Thread.Sleep, but they seem to make no difference.