C#中的TaskCompletionSource<TResult>

  1. Represents the producer side of a Task<TResult> unbound to a delegate, providing access to the consumer side through the Task property.

参考资料:

https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource-1?redirectedfrom=MSDN&view=netframework-4.8

以下为本人调试时的代码:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TaskCompletionSource_TResult
{
    class Program
    {
        //Demonstrated features:
        //    TaskCompletionSource ctor()
        //    TaskCompletionSource.SetResult()
        //    TaskCompletionSource.SetException()
        //    Task.Result
        //Expected results:
        //    The attempt to get t1.Result blocks for 1000ms until tcs1 gets signaled. 15 is print out.
        //    The attempt to get t2.Result blocks for 1000ms until tcs2 gets signaled. An exception is print out.
        static void Main(string[] args)
        {
            TaskCompletionSource<int> tcs1 = new TaskCompletionSource<int>();
            Task<int> t1 = tcs1.Task;

            //Start a background task that will complete tcs1.Task
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(1000);
                tcs1.SetResult(15);
            });

            //The attempt to get the result of t1 blocks the current thread until the completion source gets signaled.
            //It should be a wait of 1000 ms.
            Stopwatch sw = Stopwatch.StartNew();
            int result = t1.Result;
            sw.Stop();

            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " (ElapsedTime = " + sw.ElapsedMilliseconds + "), t1.result = " + result + " (expected 15)");

            //------------------------------------------------------------------------------------------------------------

            //Alternatively, an exception can be manually set on a TaskCompletionSource.Task
            TaskCompletionSource<int> tcs2 = new TaskCompletionSource<int>();
            Task<int> t2 = tcs2.Task;

            //Start a background Task that will complete tcs2.Task with an exception
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(1000);
                tcs2.SetException(new InvalidOperationException("SIMULATED EXCEPTION"));
                tcs2.SetResult(911);
            });

            //The attempt to get the result of t2 blocks the current thread until the completion source gets signaled with either
            //a result or an exception.
            //In either case it should be a wait of 1000ms.
            sw = Stopwatch.StartNew();
            try
            {
                result = t2.Result;
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " t2.Result succeeded. THIS WAS NOT EXCEPTION.");
            }
            catch (AggregateException e)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " (ElapsedTime = " + sw.ElapsedMilliseconds + ")");
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " The following exceptions have been thrown by t2.Result : (THIS WAS EXPECTED)");
                for (int j = 0; j < e.InnerExceptions.Count; j++)
                {
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n------------------------------------------------------------------\n" + e.InnerExceptions[j].ToString());
                }
            }

            Console.ReadLine();
        }
    }
}

运行结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值