将异步回调与 Task.ContinueWith 一起使用 [英] Use an async callback with Task.ContinueWith

查看:22
本文介绍了将异步回调与 Task.ContinueWith 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C# 的 async/await/continuewith.我的目标是必须有 2 个并行运行的任务,尽管哪个任务正在按顺序执行一系列操作.为此,我计划有一个 List 来表示并行运行的 2 个(或更多)任务,并在每个 上使用 ContinueWith>任务我的问题是当 await taskList 已经返回时,continue with 中的回调似乎没有被执行.

I'm trying to play a bit with C#'s async/await/continuewith. My goal is to have to have 2 tasks which are running in parallel, though which task is executing a sequence of action in order. To do that, I planned to have a List<Task> that represent the 2 (or more) tasks running in parallel, and to use ContinueWith on each of the Task My problem is that the callback in continue with seems not to be executed while the await taskList has already returned.

为了总结,这里有一个示例来说明我期望发生的事情:

In order to summarize, here's a sample to illustrate what I'm expecting to happen:

class Program
{
    static public async Task Test()
    {
        System.Console.WriteLine("Enter Test");
        await Task.Delay(100);
        System.Console.WriteLine("Leave Test");
    }

    static void Main(string[] args)
    {
        Test().ContinueWith(
        async (task) =>
        {
            System.Console.WriteLine("Enter callback");
            await Task.Delay(1000);
            System.Console.WriteLine("Leave callback");
        },
        TaskContinuationOptions.AttachedToParent).Wait();
        Console.WriteLine("Done with test");
    }
}

预期的输出是

Enter Test
Leave Test
Enter callback
Leave callback
Done with test

然而,输出是

Enter Test
Leave Test
Enter callback
Done with test

有没有办法让调用 ContinueWith 的任务在被认为完成之前等待提供的函数完成?IE..Wait 会等待两个任务都完成,原来的一个,ContinueWith 返回的一个

Is there a way to make the Task on which ContinueWith is called wait for the provided function to complete before being considered as done? ie. .Wait will wait for both tasks to be completed, the original one, and the one which is returned by ContinueWith

推荐答案

当使用 ContinueWith 方法链接多个任务时,您的返回类型将为 TaskT 是传递给 ContinueWith 的委托/方法的返回类型.

When chaining multiple tasks using the ContinueWith method, your return type will be Task<T> whereas T is the return type of the delegate/method passed to ContinueWith.

由于异步委托的返回类型是 Task,您最终会得到一个 Task 并最终等待异步委托返回您在第一个 await 之后完成的 Task.

As the return type of an async delegate is a Task, you will end up with a Task<Task> and end up waiting for the async delegate to return you the Task which is done after the first await.

为了纠正这种行为,您需要使用嵌入在您的 Task 中的返回的 Task.使用 Unwrap 扩展方法来提取它.

In order to correct this behaviour, you need to use the returned Task, embedded in your Task<Task>. Use the Unwrap extension method to extract it.

这篇关于将异步回调与 Task.ContinueWith 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆