我正在根据其他一些数据构建一系列Actions.每个操作都应该调用方法,并且应该并行执行操作列表.我有以下代码适用于无参数方法:
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");
}
Run Code Online (Sandbox Code Playgroud)
但是,如果方法有参数,我怎么能做类似的事呢?以下不起作用:
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);
}
Run Code Online (Sandbox Code Playgroud)
只需将actions变量保留为a List<Action>而不是a 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);
}
Run Code Online (Sandbox Code Playgroud)
你想要的原因Action是你在调用动作时没有传递参数- 你提供参数值作为委托定义的一部分(注意委托参数被改为没有输入参数的lambda - () => DoSomething(i)),所以这是一个Action,而不是一个Action<int>.