Run the task using the action with multiple args templates

I need to run Task in C # to create an action object.

private Action<int, int, int> action = (int p1, int p2, int p3) => { // do some stuff with p1, p2 and p3. }; 

However, when I try to create a task from it, I understand that the new Task can only accept Action or Action<object> and refuses to accept my Action with it a few template arguments.

Do you have any idea how I can create this task object and pass arguments to me?

+4
source share
2 answers

Just use lambda to convert to the delegate type you need:

 Action<int, int, int> action = (int p1, int p2, int p3) => { // do some stuff with p1, p2 and p3. }; //a closure can capture over any values you might want to pass in Task.Run(() => action(1, 2, 3)); 

If you think about this, you cannot pass Action<int, int, int> to Task.Run because you also need to provide parameters. Task.Run cannot know what you want to pass.

+5
source

How about creating a class as a DTO for your parameters?

 public class ParamDto { public string Param1; . . . } 
-2
source

Source: https://habr.com/ru/post/1446190/


All Articles