TaskCompletionSource使用心得

首先,贴代码

class Program
    {
        static void Main()
        {
            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);
                Console.WriteLine("第一个Factory" + Thread.CurrentThread.ManagedThreadId);
            });

            // 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;
            Console.WriteLine("主1:"+Thread.CurrentThread.ManagedThreadId);
            sw.Stop();

            Console.WriteLine("(ElapsedTime={0}): t1.Result={1} (expected 15) ", sw.ElapsedMilliseconds, result);

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

            // 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"));
                Console.WriteLine("第二个Factory" + Thread.CurrentThread.ManagedThreadId);
            });

            // 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 ~1000 ms.
            sw = Stopwatch.StartNew();
            try
            {
                result = t2.Result;

                Console.WriteLine("t2.Result succeeded. THIS WAS NOT EXPECTED.");
            }
            catch (AggregateException e)
            {
                Console.WriteLine("AggregateException:" + Thread.CurrentThread.ManagedThreadId);
                Console.Write("(ElapsedTime={0}): ", sw.ElapsedMilliseconds);
                Console.WriteLine("The following exceptions have been thrown by t2.Result: (THIS WAS EXPECTED)");
                for (int j = 0; j < e.InnerExceptions.Count; j++)
                {
                    Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());
                }

            }
            Console.WriteLine("主2:" + Thread.CurrentThread.ManagedThreadId);
            Console.ReadKey();
        }
    }

1,int result = t1.Result;//要等待 t1.Result的结果值

2,tcs1.SetResult(15);//tcs1.SetResult(15);设置t1.Result的结果值

3,tcs1.SetResult(15);执行后才会执行int result = t1.Result;。否则就会一直停在int result = t1.Result;

4,可以看出是不同线程间返回的值

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: TaskCompletionSource是一个.NET中的类,它允许您创建一个Task对象,并在某个时间点手动完成该任务。这个类通常用于异步编程中,当您需要在异步操作完成后手动完成一个任务时,可以使用TaskCompletionSource。它提供了一种简单的方式来创建和管理异步操作的结果。 ### 回答2: TaskCompletionSource是一个用于创建和控制异步任务的类。它提供了一种将异步操作与Task对象进行关联的方法。 通常,我们使用异步方法来执行一些耗时的操作,例如从网络下载数据或执行长时间运算。TaskCompletionSource提供了一种将这样的异步操作封装到Task对象中的方式。 我们可以通过实例化TaskCompletionSource对象来创建一个与之关联的Task对象。然后,可以使用TaskCompletionSource的方法来控制Task对象的状态和结果。 TaskCompletionSource类提供了以下几种常用的方法: 1. SetResult: 使用此方法表示任务已成功完成,并提供任务的结果。 2. SetException: 使用此方法表示任务发生了异常,并提供相应的异常信息。 3. SetCancelled: 使用此方法表示任务已被取消。 4. Task: 通过访问Task属性,我们可以获取与TaskCompletionSource关联的Task对象,从而可以监视任务的执行状态和获取任务的执行结果。 使用TaskCompletionSource,我们可以更方便地使用异步操作,简化代码逻辑,并且可以更好地控制任务的执行。 总结起来,TaskCompletionSource是一个强大的工具,用于创建和控制异步任务。它使得异步操作的管理和编写变得更加简单和灵活。使用TaskCompletionSource,我们可以将异步操作封装到Task对象中,并通过控制TaskCompletionSource来控制任务的执行状态和结果。 ### 回答3: TaskCompletionSource 是 .NET Framework 中的一种类型,用于处理异步操作的完成和结果返回。 在进行异步编程时,通常需要使用异步方法、任务或者线程来执行一些耗时的操作,而 TaskCompletionSource 就是为了更好地处理这些异步操作而引入的。 TaskCompletionSource 具有两个主要的功能,一是允许我们手动创建一个 Task,并在某个时候告知这个 Task 的完成情况;二是可以通过 TaskCompletionSource 的 Result 属性来获取这个 Task 的结果。 下面以示例来说明 TaskCompletionSource 的用法。 ``` public async Task<string> GetDataAsync() { TaskCompletionSource<string> tcs = new TaskCompletionSource<string>(); // 模拟一个异步操作 await Task.Delay(1000); // 设置 Task 的结果,并将状态设置为完成 tcs.SetResult("Hello World!"); // 返回 Task,供外部使用 return await tcs.Task; } ``` 在这个示例中,通过 TaskCompletionSource 手动构造了一个 Task,并在异步操作完成后使用 SetResult 方法来设置 Task 的结果。 通过调用 GetDataAsync 方法,我们可以获得一个 Task<string> 对象。当异步操作完成后,我们可以通过 await 运算符来获取异步操作的结果。 总之,TaskCompletionSource 提供了一种手动创建和管理 Task 的机制,使得我们可以灵活地处理异步操作的完成和结果返回。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值