gpt4 book ai didi

c# - 为什么 TaskCompleted 在操作结束之前执行

转载 作者:行者123 更新时间:2023-12-05 03:24:06 26 4
gpt4 key购买 nike

我创建了一个类似下面代码的任务

Task task = new(async () =>
{
// without await Task Delay dont work
await Task.Delay(TimeSpan.FromSeconds(5));
Console.WriteLine("Task is down");
});

task.Start();

var awaiter = task.GetAwaiter();

awaiter.OnCompleted(() =>
{
Console.WriteLine("Task is Completed");
});

为什么打印任务先完成后任务down任务完成,如果我的操作还没有完成,将打印

最佳答案

因为 Task 构造函数不支持异步。没有重载采用返回 Task 的函数,因此通过构造函数和异步 lambda 创建的任务将在遇到第一个 await(未完成的任务)时立即完成。

一般来说,您应该尽量避免使用 Task 构造函数,而更喜欢使用 Task.Run。来自docs :

This constructor should only be used in advanced scenarios where it is required that the creation and starting of the task is separated.
Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action) or TaskFactory.StartNew(Action) method.

关于c# - 为什么 TaskCompleted 在操作结束之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72350919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com