[官方文档] System.Threading.Tasks 命名空间
[官方文档] Task.GetAwaiter()
using System; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Threading; namespace ConsoleApp11 { internal class Program { static void Main(string[] args) { //创建任务 Task<int> task = new Task<int>(() => { Thread.Sleep(3000); Console.WriteLine("执行任务"); return 5; }); //启动任务 task.Start(); //获取等待器 TaskAwaiter<int> awaiter = task.GetAwaiter(); //当任务完成后将触发OnCompleted和UnsafeOnCompleted //注意:任务发生未经处理的异常,任务被终止,也算完成任务。 awaiter.OnCompleted(() => { Console.WriteLine("TaskAwaiter OnCompleted"); }); awaiter.UnsafeOnCompleted(() => { Console.WriteLine("TaskAwaiter UnsafeOnCompleted"); }); //GetResult()会等待任务完成 int result = awaiter.GetResult(); if (awaiter.IsCompleted) Console.WriteLine("结果: {0}", result); Console.ReadLine(); } } }