gpt4 book ai didi

c# - 有人可以解释这里发生的Parallel.ForEach循环逻辑吗?

转载 作者:行者123 更新时间:2023-12-03 13:16:55 25 4
gpt4 key购买 nike

我只是在尝试学习执行线程/任务的不同方法,我想要一种动态更改正在执行的任务的方法,并指出了Parallel.ForEach循环。我做了一个小例子程序,我有几个问题。

public void StartTest()
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 6; i++)
{
actions.Add(() => Function1("Word: " + i));
}
Parallel.ForEach(actions, new ParallelOptions
{
MaxDegreeOfParallelism = 2
}, action => action());

Console.WriteLine("Finished. \nTime Taken: " + total.ToString(@"dd\.hh\:mm\:ss"));
Console.Read();
}


private void Function1(string word)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(word + " | Task Id: " + Task.CurrentId + " | " + i);
}
Console.WriteLine(word + " ----- Completed.");
}

所以我的第一个问题是循环的“action => action()”块是做什么的?我知道lambda是什么,但实际上我只是不遵循这一点。

我的第二个问题是为什么这是输出?

字:6 |任务ID:3 | 0

字:6 |任务ID:3 | 1个

字:6 |任务ID:3 | 2个

字:6 |任务ID:3 | 3

字:6 |任务ID:3 | 4

字:6 -----已完成。

字:6 |任务ID:3 | 0

字:6 |任务ID:3 | 1个

字:6 |任务ID:3 | 2个

字:6 |任务ID:3 | 3

字:6 |任务ID:3 | 4

字:6 -----已完成。

字:6 |任务ID:3 | 0

字:6 |任务ID:3 | 1个

字:6 |任务ID:3 | 2个

字:6 |任务ID:3 | 3

字:6 |任务ID:3 | 4

字:6 -----已完成。

字:6 |任务ID:3 | 0

字:6 |任务ID:3 | 1个

字:6 |任务ID:3 | 2个

字:6 |任务ID:3 | 3

字:6 |任务ID:3 | 4

字:6 -----已完成。

字:6 |任务ID:3 | 0

字数:6 |任务ID:3 | 1个

字:6 |任务ID:3 | 2个

字:6 |任务ID:2 | 0

字:6 |任务ID:2 | 1个

字:6 |任务ID:2 | 2个

字:6 |任务ID:2 | 3

字:6 |任务ID:2 | 4

字:6 -----已完成。

字:6 |任务ID:3 | 3

字:6 |任务ID:3 | 4

字:6 -----已完成。

完成的。

花费时间:00.00:00:00

为什么每个数字都是6?我了解线程的工作方式,但不了解参数的传递/引用。

这就是我的两个问题。任何帮助都将是极好的。我在Google搜索了一段时间,找不到对我有意义的任何文档。

最佳答案

public void StartTest()
{
var actions = new List<Action>();
for (int i = 0; i < 6; i++)
{
// you can't pass 'i' directly to the Action here,
// because 'i' is in the scope of where the Action is executed
// and since the parameter of the Action is first evaluated at the
// execution of the Action if you were to put 'i' it checks what value
// 'i' has at the current point in time and since the for-loop finished
// already it is always going to be 6
var word = $"Word: {i}";
actions.Add(() => Function1(word));
}

// you could interpret the lambda 'action => action()' as
// foreach(var action in actions)
// action();
// so it essentially tells you what it's going to do for each
// Action Item in the Action-Collection you passed as Parallel.ForEach's first parameter,
// while 'action' represents the "current" item
Parallel.ForEach(actions, new ParallelOptions{MaxDegreeOfParallelism = 2}, action => action());

Console.WriteLine("Finished. \nTime Taken: " + total.ToString(@"dd\.hh\:mm\:ss"));
Console.Read();
}


private void Function1(string word)
{
for (int i = 0; i < 5; i++)
Console.WriteLine(word + " | Task Id: " + Task.CurrentId + " | " + i);

Console.WriteLine(word + " ----- Completed.");
}

关于c# - 有人可以解释这里发生的Parallel.ForEach循环逻辑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526969/

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