为什么 TaskCompleted 在操作结束之前执行
Why the TaskCompleted is executed before the end of the operation
我创建了一个类似下面代码的任务
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.
我创建了一个类似下面代码的任务
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 staticTask.Run(Action)
orTaskFactory.StartNew(Action)
method.