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

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

问题描述

我尝试在为它注册延续后开始一项任务.但是在 await Task.Delay() 被调用后,continuation 会立即触发.

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 委托.正如我在我的博客中所描述的,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天全站免登陆