Create List of actions already passing the parameters and then execute them according to parameters passed

0

I wanted to know if there is a possibility to create a list of Actions already passing their parameters to execute, because the numbers that I will pass to the execution of them can be variable, so I would like to save these aActions already with their parameters for later only run them all at once.

Here's an example:

    public class Program
{
    private static List<Task> ListActions = new List<Task>();

    static void Main(string[] args)
    {
        ExecuteMethod();
        ExecuteListDeActions();
    }

    private static void ExecuteMethod()
    {
        int loop = 10;


        while (loop > 0)
        {
            int valor1 = new Random().Next();
            int valor2 = new Random().Next();
            int valor3 = new Random().Next();

            ListActions.Add(new Task(() => MinhaAction(valor1, valor2, valor3)));

            loop--;
        }
    }

    private async static Task<int> MinhaAction(int valor1, int valor2, int valor3)
    {
        Console.WriteLine("-------------------");
        Console.WriteLine("Numero 1: " + valor1);
        Console.WriteLine("Numero 2: " + valor2);
        Console.WriteLine("Numero 3: " + valor3);
        Console.WriteLine("-------------------");

        return valor1 + valor2 + valor3;
    }

    private async static void ExecuteListDeActions()
    {
        foreach(var a in ListActions)
        {
            a.Start();
        }
        Console.ReadLine();
    }
}
    
asked by anonymous 22.02.2018 / 15:14

1 answer

1

I think in your case it is better to use Task, since you have an interest in running all at once.

Reference

public class Program
{
    private List<Task> ListActions = new List<Task>();

    public void Main(string[] args)
    {
        var rand = new Random();
        int valor1 = rand.Next();
        int valor2 = rand.Next();
        int valor3 = rand.Next();
        Task t = Task.Run(() => MinhaAction(valor1, valor2, valor3));
        ListActions.Add(t);
    }

    private int MinhaAction(int valor1, int valor2, int valor3)
    {
        return valor1 + valor2 + valor3;
    }

    private void ExecuteListDeActions()
    {
        Task.WaitAll(ListActions.ToArray());
        foreach (Task t in ListActions)
            Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);

        Console.WriteLine("T: {0}", ListActions.Count);
    }
}
    
22.02.2018 / 15:20