TaskCompletionSource

作者:追风剑情 发布于:2023-8-4 15:07 分类:C#

using System;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var sourceTask = DoSomthing();
            try
            {
                //当调用Result时,任务会挂起,直到完成后才返回
                Console.WriteLine("Async completed: {0}", sourceTask.Task.Result);
            }
            catch(AggregateException e)
            {
                //当任务取消或发生异常时会抛出AggregateException
                //e.Message: 发生一个或多个错误
                Console.WriteLine(e.Message);
                //e.InnerException.Message: 具体的错误原因描述在这里
                Console.WriteLine(e.InnerException.Message);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Main End");
            Console.Read();
        }

        public static TaskCompletionSource<string> DoSomthing()
        {
            TaskCompletionSource<string> source = new TaskCompletionSource<string>();
            
            Task.Run(()=> {
                //暂停5秒
                Task delay = Task.Delay(5000);
                delay.Wait();
                //TaskCompletionSource完成
                //source.SetResult("Hello world!");

                //取消任务,会向外部程序抛出 AggregateException
                //外部程序通过 aggregateException.InnerException.Message 打印报错消息
                //source.SetCanceled();

                //设置异常,会向外部程序抛出 AggregateException
                //外部程序通过 aggregateException.InnerException.Message 打印自定义报错消息
                source.SetException(new Exception("my exception message"));
            });
            
            Console.WriteLine("DoSomthing() End");
            return source;
        }
    }
}

运行测试

(1) 调用SetResult(),正常结束

1111.png

(2) 调用SetCanceled(),取消任务

22222.png

(3) 调用SetException(),发生异常

33333.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号