Task.GetAwaiter()

作者:追风剑情 发布于:2024-1-19 17:23 分类:C#

[官方文档] 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

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号