简体   繁体   English

执行异步任务列表

[英]Execute list of async tasks

I have a list of async functions I want to execute in order. 我有一个要按顺序执行的异步函数列表。 When I run the following code I get the output: 当我运行以下代码时,我得到输出:

Task 1 before
Task 2 before
Finished tasks

Why are my async functions not being awaited correctly? 为什么我的异步功能未正确等待?

    [Test]
    public async Task AsyncTaskList()
    {
        var data = "I'm data";
        var tasks = new List<Func<object, Task>>() {Task1, Task2};

        tasks.ForEach(async task =>
        {
            await task(data);
        });

        Debug.WriteLine("Finished tasks");
    }

    private static async Task Task1(object data)
    {
        Debug.WriteLine("Task 1 before");
        await Task.Delay(1000);
        Debug.WriteLine("Task 1 after");
    }

    private static async Task Task2(object data)
    {
        Debug.WriteLine("Task 2 before");
        await Task.Delay(1000);
        Debug.WriteLine("Task 2 after");
    }

Because the await inside your ForEach delegate actually completes after the method exits. 因为您的ForEach委托中的await实际上方法退出完成。 Change it to an actual foreach loop and awaiting will work as expected. 将其更改为实际的foreach循环,等待将按预期工作。

ForEach has no specific handling for Func<Task> (few delegate-accepting methods in the Base Class Library do, and you should note that they will almost invariably return a Task themselves). ForEach没有对Func<Task>特定处理(基类库中很少有委托接受方法,您应该注意,它们几乎总是会自己返回Task )。 ForEach will only run the synchronous portion of your lambda - and that is the portion preceding the first await of a Task which does not complete synchronously (which is Task.Delay in your case). ForEach将仅运行lambda的同步部分-这是Task第一次await 之前未同步完成的部分(在您的情况下为Task.Delay )。 This is why you're seeing the "before" messages popping up at the expected time. 这就是为什么您会在预期的时间看到“之前”消息的原因。 As soon as your delegate hits await Task.Delay , the the rest of your lambda is scheduled to run sometime in the future and ForEach moves on to the next item in the list. 一旦您的代表点击await Task.Delay ,其余lambda就会安排在将来的某个时间运行,并且ForEach移至列表中的下一项。 The scheduled task continuations will then run unobserved and complete later. 计划的任务继续将在未观察到的情况下运行,并在以后完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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