我正在根据其他一些数据构建一个操作列表。每个 Action 都应该调用一个方法,并且 Action 列表应该并行执行。我有以下代码,适用于无参数方法:
private void Execute() {
List<Action> actions = new List<Action>();
for (int i = 0; i < 5; i++) {
actions.Add(new Action(DoSomething));
}
Parallel.Invoke(actions.ToArray());
}
private void DoSomething() {
Console.WriteLine("Did something");
}
但是我怎样才能在方法有参数的情况下做类似的事情呢?以下不起作用:
private void Execute() {
List<Action<int>> actions = new List<Action<int>>();
for (int i = 0; i < 5; i++) {
actions.Add(new Action(DoSomething(i))); // This fails because I can't input the value to the action like this
}
Parallel.Invoke(actions.ToArray()); // This also fails because Invoke() expects Action[], not Action<T>[]
}
private void DoSomething(int value) {
Console.WriteLine("Did something #" + value);
}
最佳答案
只需保留您的 actions
变量为 List<Action>
而不是 List<Action<int>>
两个问题都解决了:
private void Execute() {
List<Action> actions = new List<Action>();
for (int i = 0; i < 5; i++) {
actions.Add(new Action(() => DoSomething(i))); }
Parallel.Invoke(actions.ToArray());
}
private void DoSomething(int value) {
Console.WriteLine("Did something #" + value);
}
你想要的原因Action
是因为您在调用操作时没有传递参数 - 您正在提供参数值作为委托(delegate)定义的一部分(请注意,委托(delegate)参数已更改到没有输入参数的 lambda - () => DoSomething(i)
),所以它是一个 Action
,不是 Action<int>
.
关于c# - 执行带有参数的动态 Action 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882931/