执行带参数的动态动作列表 [英] Executing dynamic list of Actions with parameters

查看:96
本文介绍了执行带参数的动态动作列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于其他一些数据构建一个动作列表.每个动作都应调用一个方法,并且动作列表应并行执行.我有以下代码对无参数方法非常有效:

I'm building a list of Actions based on some other data. Each action should do a call to a method, and the list of actions should be performed in parallel. I have the following code that works just fine for parameterless methods:

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");
}

但是,如果方法具有参数,我该如何做类似的事情?以下内容不起作用:

But how can I do something similar where the methods have parameters? The following does not work:

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>>即可解决这两个问题:

Just keep your actions variable as a List<Action> instead of a List<Action<int>> and both problems are solved:

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的原因是因为在调用动作时没有传递参数 -您要提供参数值作为委托定义的一部分(请注意,委托参数已更改为没有输入参数的lambda-() => DoSomething(i)),因此它是Action,而不是Action<int>.

The reason you want Action is becuase you're not passing the parameter when the action is invoked - you're providing the parameter value as part of the delegate definition (note that the delegate parameter is changed to a lambda with no input parameters - () => DoSomething(i)), so it's an Action, not an Action<int>.

这篇关于执行带参数的动态动作列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆