Task.ContinueWith在任务完成前触发 [英] Task.ContinueWith fires before task is finished

查看:82
本文介绍了Task.ContinueWith在任务完成前触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我为任务注册延续后,我正尝试启动该任务.但是,在 await Task.Delay()被调用之后,立即触发继续操作.

I'm trying to start a task after I register a continuation for it. But continuation fires immediately after await Task.Delay() is called.

using System;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApplication30
{
    class Program
    {
        static void Main(string[] args)
        {
            var task = new Task(async delegate {
                Console.WriteLine("Before delay");
                await Task.Delay(1000);
                Console.WriteLine("After delay");
            });

            task.ContinueWith(t => {
                Console.WriteLine("ContinueWith");
            });

            task.Start();

            Console.ReadLine();
        }
    }
}

输出:

Before delay
ContinueWith
After delay

这是怎么了?

推荐答案

您的问题-正如其他人所指出的-是 Task.Task 无法理解 async 委托.正如我在博客中所述,code> Task 构造函数永远不要使用-它实际上有个用例.

Your problem - as others have noted - is that Task.Task does not understand async delegates. As I describe on my blog, the Task constructor should never be used - it has literally zero use cases.

如果要在线程池线程上运行代码,请使用 Task.Run .

If you want to run code on a thread pool thread, use Task.Run.

此外,您不应使用 ContinueWith ;这是一个非常低级且危险的API(如我的博客所述).您应该改用 await .

class Program
{
    static void Main(string[] args)
    {
        MainAsync().Wait();
    }

    static async Task MainAsync()
    {
        var task = Task.Run(async delegate {
            Console.WriteLine("Before delay");
            await Task.Delay(1000);
            Console.WriteLine("After delay");
        });

        await task;
        Console.WriteLine("await");

        Console.ReadLine();
    }
}

这篇关于Task.ContinueWith在任务完成前触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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