gpt4 book ai didi

c# - 使用不同的参数并行运行相同的代码多次

转载 作者:行者123 更新时间:2023-12-03 15:21:17 25 4
gpt4 key购买 nike

这个非常简单的例子:

        int numLanes = 8;
var tasks = new List<Task>();
for (var i = 0; i < numLanes; ++i)
{
var t = new Task(() =>
{
Console.WriteLine($"Lane {i}");
});
tasks.Add(t);
}
tasks.ForEach((t) => t.Start());
Task.WaitAll(tasks.ToArray());

产生:
Lane 8
Lane 8
Lane 8
Lane 8
Lane 8
Lane 8
Lane 8
Lane 8

这不是预期的,参数 i没有正确通过。我曾想过使用 Action<int>包装代码,但看不到我会怎么做。我不想写像 Task CreateTask(int i)这样的专用方法我对如何使用 lambda 表达式感兴趣。

执行此操作的正常方法是什么 - 使用不同的参数值并行地多次启动相同的代码?

最佳答案

你有一个捕获的循环变量 i ,尝试在循环中添加临时变量并将其传递给 Task

for (var i = 0; i < numLanes; ++i)
{
var temp = i;
var t = new Task(() =>
{
Console.WriteLine($"Lane {temp}");
});
tasks.Add(t);
}

进一步阅读 How to capture a variable in C# and not to shoot yourself in the foot . foreach循环在 C# 5 之前具有相同的行为,但根据上面的链接

with the release of the C# 5.0 standard this behavior was changed by declaring the iterator variable inside every loop iteration, not before it on the compilation stage, but for all other constructions similar behavior remained without any changes



因此,您可以使用 foreach没有临时变量

关于c# - 使用不同的参数并行运行相同的代码多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61343062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com