[英]Convert Action<T, T, T> to Task<T, T, T>?
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?我有一个Action
列表,我想使用async/await
,但我不知道如何将以下代码(简化示例)转换为使用 af Task
列表? 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.重要的是,我需要以某种方式获取每个任务中的操作名称,并确保在ForEach
循环内继续执行下一个任务之前完成任务。 My code runs in Main
in Program
.我的代码在Program
中的Main
中运行。
Note: The actions are being invoked with 3 parameters, so I need the tasks to be also "invoked" similarly with the same parameters.注意:使用 3 个参数调用操作,因此我需要使用相同的参数类似地“调用”任务。
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!先感谢您!
Here's a version that runs the work sequentially:这是一个按顺序运行工作的版本:
public static async Task Main()
{
// Action<string,string,string> becomes
// Func<string,string,string, Task> because the worker methods
// return a Task, not void
var work = new List<Func<string, string, string, Task>>()
{
X,
X2,
};
foreach(var t in work)
{
Console.WriteLine("Invoking action: " + t.Method.Name + " ...");
await t("Hello", "World", "!").ConfigureAwait(false);
};
}
With和
static async Task X(string a, string b, string c)
{
await Task.Delay(TimeSpan.FromMilliseconds(1)).ConfigureAwait(false);
Console.WriteLine($"{a} {b} {c}");
}
static async Task X2(string a, string b, string c)
{
await Task.Delay(TimeSpan.FromMilliseconds(1)).ConfigureAwait(false);
Console.WriteLine($"{c} {b} {a}");
}
this prints这打印
Invoking action: X ...
Hello World !
Invoking action: X2 ...
! World Hello
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.