TaskCompletionSource<TResult> 类

定义

表示未绑定到委托的 Task<TResult> 的制造者方,并通过 Task 属性提供对使用者方的访问。Represents the producer side of a Task<TResult> unbound to a delegate, providing access to the consumer side through the Task property.

generic <typename TResult>
public ref class TaskCompletionSource
public class TaskCompletionSource<TResult>
type TaskCompletionSource<'Result> = class
Public Class TaskCompletionSource(Of TResult)

类型参数

TResult

与此 @no__t 关联的结果值的类型。The type of the result value associated with this TaskCompletionSource<TResult>.

继承
TaskCompletionSource<TResult>

示例

下面的示例演示如何使用 TaskCompletionSource<TResult>The following example shows how to use a 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());
            }
        }
    }

}
Imports System.Diagnostics
Imports System.Threading
Imports System.Threading.Tasks

Module 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.

    Private Sub Main()
        Dim tcs1 As New TaskCompletionSource(Of Integer)()
        Dim t1 As Task(Of Integer) = tcs1.Task

        ' Start a background task that will complete tcs1.Task
        Task.Factory.StartNew(Sub()
                                  Thread.Sleep(1000)
                                  tcs1.SetResult(15)
                              End Sub)

        ' 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.
        Dim sw As Stopwatch = Stopwatch.StartNew()
        Dim result As Integer = 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
        Dim tcs2 As New TaskCompletionSource(Of Integer)()
        Dim t2 As Task(Of Integer) = tcs2.Task

        ' Start a background Task that will complete tcs2.Task with an exception
        Task.Factory.StartNew(Sub()
                                  Thread.Sleep(1000)
                                  tcs2.SetException(New InvalidOperationException("SIMULATED EXCEPTION"))
                              End Sub)

        ' 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 e As AggregateException
            Console.Write("(ElapsedTime={0}): ", sw.ElapsedMilliseconds)
            Console.WriteLine("The following exceptions have been thrown by t2.Result: (THIS WAS EXPECTED)")
            For j As Integer = 0 To e.InnerExceptions.Count - 1
                Console.WriteLine(vbLf & "-------------------------------------------------" & vbLf & "{0}", e.InnerExceptions(j).ToString())
            Next
        End Try
    End Sub

End Module

注解

在许多情况下,启用 Task<TResult> 以表示外部异步操作非常有用。In many scenarios, it is useful to enable a Task<TResult> to represent an external asynchronous operation. 为此,提供 TaskCompletionSource<TResult>TaskCompletionSource<TResult> is provided for this purpose. 它允许创建可以向使用者传递的任务。It enables the creation of a task that can be handed out to consumers. 使用者可以使用任务的成员,其方式与处理任务成员变量的任何其他方案相同。The consumers can use the members of the task the same way as they would in any other scenario handling task member variables. 但是,与大多数任务不同,TaskCompletionSource 创建的任务的状态由 TaskCompletionSource 上的方法显式控制。However, unlike most tasks, the state of a task created by a TaskCompletionSource is controlled explicitly by the methods on TaskCompletionSource. 这样就可以完成外部异步操作以传播到基础任务。This enables the completion of the external asynchronous operation to be propagated to the underlying Task. 分隔还可确保使用者不能在不访问相应 TaskCompletionSource 的情况下转换状态。The separation also ensures that consumers are not able to transition the state without access to the corresponding TaskCompletionSource. 有关详细信息,请参阅TaskCompletionSource @ no__t-> 1TResult 的性质.Net 博客并行编程中的内容。For more information, see the entry The Nature of TaskCompletionSource<TResult> in the Parallel Programming with .NET blog.

并行扩展示例还包含了有关如何使用 TaskCompletionSource<TResult> 的示例。The Parallel Extensions samples also contain examples of how to use TaskCompletionSource<TResult>.

构造函数

TaskCompletionSource<TResult>()

创建一个 TaskCompletionSource<TResult>Creates a TaskCompletionSource<TResult>.

TaskCompletionSource<TResult>(Object)

使用指定的状态创建一个 TaskCompletionSource<TResult>Creates a TaskCompletionSource<TResult> with the specified state.

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

使用指定的状态和选项创建一个 TaskCompletionSource<TResult>Creates a TaskCompletionSource<TResult> with the specified state and options.

TaskCompletionSource<TResult>(TaskCreationOptions)

使用指定的选项创建一个 TaskCompletionSource<TResult>Creates a TaskCompletionSource<TResult> with the specified options.

属性

Task

获取由此 Task<TResult> 创建的 TaskCompletionSource<TResult>Gets the Task<TResult> created by this TaskCompletionSource<TResult>.

方法

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
SetCanceled()

将基础 Task<TResult> 转换为 Canceled 状态。Transitions the underlying Task<TResult> into the Canceled state.

SetException(Exception)

将基础 Task<TResult> 转换为 Faulted 状态,并将其绑定到一个指定异常上。Transitions the underlying Task<TResult> into the Faulted state and binds it to a specified exception.

SetException(IEnumerable<Exception>)

将基础 Task<TResult> 转换为 Faulted 状态,并对其绑定一些异常对象。Transitions the underlying Task<TResult> into the Faulted state and binds a collection of exception objects to it.

SetResult(TResult)

将基础 Task<TResult> 转换为 RanToCompletion 状态。Transitions the underlying Task<TResult> into the RanToCompletion state.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
TrySetCanceled()

尝试将基础 Task<TResult> 转换为 Canceled 状态。Attempts to transition the underlying Task<TResult> into the Canceled state.

TrySetCanceled(CancellationToken)

尝试将基础 Task<TResult> 转换为 Canceled 状态并启用要存储在取消的任务中的取消标记。Attempts to transition the underlying Task<TResult> into the Canceled state and enables a cancellation token to be stored in the canceled task.

TrySetException(Exception)

尝试将基础 Task<TResult> 转换为 Faulted 状态,并将其绑定到一个指定异常上。Attempts to transition the underlying Task<TResult> into the Faulted state and binds it to a specified exception.

TrySetException(IEnumerable<Exception>)

尝试将基础 Task<TResult> 转换为 Faulted 状态,并对其绑定一些异常对象。Attempts to transition the underlying Task<TResult> into the Faulted state and binds a collection of exception objects to it.

TrySetResult(TResult)

尝试将基础 Task<TResult> 转换为 RanToCompletion 状态。Attempts to transition the underlying Task<TResult> into the RanToCompletion state.

适用于

线程安全性

@No__t 的所有成员都是线程安全的,可同时从多个线程使用。All members of TaskCompletionSource<TResult> are thread-safe and may be used from multiple threads concurrently.

另请参阅