I want to add multiple parameter in a Task containing Action. I reviewed the existing stack-overflow question Create a Task with an Action<T>
Kindly assist me how to pass multiple arguments in a Action method in a Task
Action<string, int> action = (string msg, int count) =>
{
Task.Factory.StartNew(async () =>
{ await LoadAsync(msg, count); });
};
Task task = new Task(action, ....);
The Action Method is
public static async Task<string> LoadAsync(string message, int count)
{
await Task.Run(() => { Thread.Sleep(1500); });
Console.WriteLine("{0} {1} Exceuted Successfully !", message ?? string.Empty, (count == 0) ? string.Empty : count.ToString());
return "Finished";
}
Kindly assist me how to Create a action of an async method and how to add the action into the Task.
Create another lambda which execute your action and pass parameters there
In particular your case you don't need create a lot of tasks and threads which will be created with
Task.Run
orStartNew
If you change your method to be asynchronous without wasting threads with
Thread.Sleep
Then you can call it anywhere without
Task.Run
Your
LoadAsync
method already returning aTask<string>
which you can start and "await" whenever you want. So you don't need to useTask.Run
to start another Task(thread in your case).Just pass the parameters like this.
If you want to also get return value