TaskCompletionSource<TResult> 類別

定義

代表未綁定的生產者側 Task<TResult> 與代理人,透過該 Task 資產提供消費者端的存取。

generic <typename TResult>
public ref class TaskCompletionSource
public class TaskCompletionSource<TResult>
type TaskCompletionSource<'Result> = class
Public Class TaskCompletionSource(Of 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());
            }
        }
    }
}
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

備註

在許多情境下,啟用 a Task<TResult> 來表示外部非同步操作是很有用的。 TaskCompletionSource<TResult> 是為此目的而提供的。 它能創造一項可分配給消費者的任務。 消費者可以像在處理任務成員變數的其他情境中一樣使用任務成員。 然而,與大多數任務不同的是,由 TaskCompletionSource 建立的任務狀態是由 TaskCompletionSource 上的方法明確控制。 這使得外部非同步操作的完成能夠傳達到底層任務。 分離也確保消費者無法在未取得對應 TaskCompletionSource 的情況下轉換狀態。 欲了解更多資訊,請參閱 Parallel Programming with .NET 部落格中的條目 The Nature of TaskCompletionSource<TResult>

建構函式

名稱 Description
TaskCompletionSource<TResult>()

建立 TaskCompletionSource<TResult>

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

建立包含指定狀態和選項的 a TaskCompletionSource<TResult>

TaskCompletionSource<TResult>(Object)

建立具有指定狀態的 。TaskCompletionSource<TResult>

TaskCompletionSource<TResult>(TaskCreationOptions)

建立包含指定選項的 a TaskCompletionSource<TResult>

屬性

名稱 Description
Task

Task<TResult> 這個 TaskCompletionSource<TResult>創造出來。

方法

名稱 Description
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

適用於

執行緒安全性

所有成員 TaskCompletionSource<TResult> 皆為執行緒安全,且可同時從多個執行緒使用。

另請參閱