繁体   English   中英

转换动作<T, T, T>到任务<T, T, T> ?

[英]Convert Action<T, T, T> to Task<T, T, T>?

我有一个Action列表,我想使用async/await ,但我不知道如何将以下代码(简化示例)转换为使用 af Task列表? 重要的是,我需要以某种方式获取每个任务中的操作名称,并确保在ForEach循环内继续执行下一个任务之前完成任务。 我的代码在Program中的Main中运行。

注意:使用 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...
});

先感谢您!

这是一个按顺序运行工作的版本:

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);
    };
}

测试

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}");
}

这打印

Invoking action: X ...
Hello World !
Invoking action: X2 ...
! World Hello

您尝试做的一个基本示例是:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM