我想在包含Action的Task中添加多个参数。我查看了现有的堆栈溢出问题Create a Task with an Action<T>
请帮助我如何在任务
中的Action方法中传递多个参数Action<string, int> action = (string msg, int count) =>
{
Task.Factory.StartNew(async () =>
{ await LoadAsync(msg, count); });
};
Task task = new Task(action, ....);
行动方法
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";
}
请帮助我如何创建异步方法的操作以及如何将操作添加到任务中。
答案 0 :(得分:3)
只需传递这样的参数。
Action<string, int> action = async (msg, count) => await LoadAsync(msg, count);
Task task = new Task(() => action("", 0)); // pass parameters you want
如果您还想获得返回值
Func<string, int, Task<string>> func = LoadAsync;
Task<string> task = func("", 0); // pass parameters you want
var result = await task; // later in async method
答案 1 :(得分:3)
创建另一个执行动作并传递参数的lambda
var task = Task.Run(() => youraction(parameter1, parameter2));
特别是在您的情况下,您不需要创建许多将使用Task.Run
或StartNew
如果将方法更改为异步而不浪费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";
}
然后您可以在没有Task.Run
await LoadAsync("", 0);
您的LoadAsync
方法已经返回Task<string>
,您可以随时启动并“等待”。因此,您不需要使用Task.Run
来启动另一个任务(在您的情况下为线程)。
var task = LoadAsync("param1", 3);
// do something else
var result = await task;