Home > OS >  Convert Action<T, T, T> to Task<T, T, T>?
Convert Action<T, T, T> to Task<T, T, T>?

Time:06-22

I have a list of Action, and I want to utilize async/await, but I don't know how to convert the following code (simplified example) to use af list of Task instead? Importantly, I need to somehow get the name of the action inside each task and also to make sure, the tasks completes before continuing to the next, inside the ForEach loop. My code runs in Main in Program.

Note: The actions are being invoked with 3 parameters, so I need the tasks to be also "invoked" similarly with the same parameters.

new List<Action<string, string, string>>()
{
   Action1,
   Action2,
   Action3,
   Action4,
   Action5
   // etc...
}.ForEach(action => {
   Console.WriteLine("Invoking action: "   action.Method.Name   " ...");
   action.Invoke("Hello", "World", "!");
   // do other stuff...
});

Thank you in advance!

CodePudding user response:

A basic example of what you are trying to do would be along the lines of:

var actions = new List<Action<string, string, string>>();
            
//....

var funcs = actions.Select(x => new Func<string, string, string, Task>((one, two, three) =>
{
    x(one, two, three);
    return Task.CompletedTask;
}));


var tasks = new List<Task>();
foreach(var func in funcs)
{
    tasks.Add(func("one", "two", "three")); //wherever these parameters come from
}

await Task.WhenAll(tasks);

CodePudding user response:

You can use a foreach loop to iterate over your list of actions. Inside the loop, you can call Task.Run to run the method in a thread from the threadpool. By using await you can make sure that every method is only invoked after the previous one is completed.

var actions = new List<Action<string, string, string>>()
{
   Action1,
   Action2,
   Action3,
   Action4,
   Action5
   // etc...
};
foreach(var action in action)
{
    await Task.Run(() =>
    {
       Console.WriteLine("Invoking action: "   action.Method.Name   " ...");
       action.Invoke("Hello", "World", "!");
       // do other stuff...
    });
}

Note: This approach only makes sense if your actions do a lot CPU-bound work.

  • Related