TaskCompletionSource<TResult> 类

定义

表示 Task<TResult> 未绑定的委托的生成方,通过 Task 属性提供对使用者端的访问权限。

public class TaskCompletionSource<TResult>

类型参数

TResult

与此 TaskCompletionSource<TResult>关联的结果值的类型。

继承
TaskCompletionSource<TResult>

示例

以下示例演示如何使用 TaskCompletionSource<TResult>

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

class TCSDemo
{
    // 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 printed out.
    // 		The attempt to get t2.Result blocks for ~1000ms until tcs2 gets signaled. An exception is printed out.
    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);
        });

        // 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("(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"));
        });

        // 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.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());
            }
        }
    }
}

注解

在许多情况下,使 Task<TResult> 能够表示外部异步操作非常有用。 为此,提供了 TaskCompletionSource<TResult>。 它允许创建可分发给使用者的任务。 使用者可以像处理任务成员变量的任何其他方案一样使用任务的成员。 但是,与大多数任务不同,TaskCompletionSource 创建的任务的状态由 TaskCompletionSource 上的方法显式控制。 这样就可以将外部异步操作的完成传播到基础任务。 分离还可确保使用者在无法访问相应的 TaskCompletionSource 的情况下无法转换状态。 有关详细信息,请参阅 .NET 并行编程博客中 TaskCompletionSource<TResult> 的条目。

并行扩展示例 还包含如何使用 TaskCompletionSource<TResult>的示例。

构造函数

属性

方法

Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
SetCanceled()

将基础 Task<TResult> 转换为 Canceled 状态。

SetCanceled(CancellationToken)

使用指定的令牌将基础 Task<TResult> 转换为 Canceled 状态。

SetException(Exception)

将基础 Task<TResult> 转换为 Faulted 状态,并将其绑定到指定的异常。

SetException(IEnumerable<Exception>)

将基础 Task<TResult> 转换为 Faulted 状态,并将异常对象的集合绑定到该状态。

SetFromTask(Task<TResult>)

将基础 Task<TResult> 转换为与指定 completedTask相同的完成状态。

SetResult(TResult)

将基础 Task<TResult> 转换为 RanToCompletion 状态。

ToString()

返回一个表示当前对象的字符串。

(继承自 Object)
TrySetCanceled()

尝试将基础 Task<TResult> 转换为 Canceled 状态。

TrySetCanceled(CancellationToken)

尝试将基础 Task<TResult> 转换为 Canceled 状态,并使取消令牌能够存储在已取消的任务中。

TrySetException(Exception)

尝试将基础 Task<TResult> 转换为 Faulted 状态,并将其绑定到指定的异常。

TrySetException(IEnumerable<Exception>)

尝试将基础 Task<TResult> 转换为 Faulted 状态,并将异常对象的集合绑定到该状态。

TrySetFromTask(Task<TResult>)

尝试将基础 Task<TResult> 转换为与指定 completedTask相同的完成状态。

TrySetResult(TResult)

尝试将基础 Task<TResult> 转换为 RanToCompletion 状态。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

线程安全性

TaskCompletionSource<TResult> 的所有成员都是线程安全的,可以同时从多个线程使用。

另请参阅