鸟语天空
Task.GetAwaiter()
post by:追风剑情 2024-1-19 17:23

[官方文档] 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();
        }
    }
}


运行测试
1111.png

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容