使用带Task.ContinueWith异步回调 [英] Use an async callback with Task.ContinueWith

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

问题描述

我试着打了一下用C#的异步/的await / continuewith。
我的目标是必须有2个任务它们并行运行,但它的任务是为了执行动作的序列。
要做到这一点,我打算有一个列表<任务> 的再present 2个(或以上)的任务并行运行,并使用 ContinueWith 工作
我的问题是,回调继续似乎并没有同时被执行伺机任务列表已经回来了。

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 方法多任务,你的返回类型为任务&LT; T&GT; ,而 T 是传递给 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.

作为异步委托的返回类型是工作,你会最终有一个任务&LT;任务&GT; 并最终等待异步委托回报你的工作这是第一个的await 后进行。

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.

为了纠正这种行为,你需要使用返回工作,嵌入在你的任务&LT;任务&GT; 。使用 展开 扩展方法来提取吧。

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天全站免登陆