Create a Task with an Action<T, T, … n> multiple parameters

ぐ巨炮叔叔 提交于 2019-12-01 12:04:48

问题


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.


回答1:


Just pass the parameters like this.

Action<string, int> action = async (msg, count) => await LoadAsync(msg, count);
Task task = new Task(() => action("", 0)); // pass parameters you want

If you want to also get return value

Func<string, int, Task<string>> func = LoadAsync;
Task<string> task = func("", 0); // pass parameters you want

var result = await task; // later in async method



回答2:


Create another lambda which execute your action and pass parameters there

var task = Task.Run(() => youraction(parameter1, parameter2));

In particular your case you don't need create a lot of tasks and threads which will be created with Task.Run or StartNew

If you change your method to be asynchronous without wasting threads with Thread.Sleep

public static async Task<string> LoadAsync(string message, int count)
{
    await Task.Delay(1500);

    var countOutput = count == 0 ? string.Empty : count.ToString();
    var output = $"{message} {countOUtput}Exceuted Successfully !";
    Console.WriteLine(output);

    return "Finished";
}

Then you can call it anywhere without Task.Run

await LoadAsync("", 0);

Your LoadAsync method already returning a Task<string> which you can start and "await" whenever you want. So you don't need to use Task.Run to start another Task(thread in your case).

var task = LoadAsync("param1", 3);
// do something  else
var result = await task;


来源:https://stackoverflow.com/questions/41520513/create-a-task-with-an-actiont-t-n-multiple-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!