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

備註

在許多情況下,啟用 Task<TResult> 來表示外部非同步作業會很有用。 TaskCompletionSource<TResult> 是為了此目的而提供。 它可讓您建立可遞交給取用者的工作。 取用者可以使用工作的成員,就像處理工作成員變數的任何其他案例一樣。 不過,與大部分的工作不同,TaskCompletionSource 所建立的工作狀態是由 TaskCompletionSource 上的方法明確控制。 這可讓外部非同步作業完成傳播至基礎工作。 分隔也可確保取用者無法在沒有對應 TaskCompletionSource 的存取權的情況下轉換狀態。 如需詳細資訊,請參閱平行程式設計與 .NET 部落格中的TaskCompletionSource <TResult> 本質一文。

平行延伸模組範例也包含如何使用 TaskCompletionSource<TResult> 的範例。

建構函式

TaskCompletionSource<TResult>()

建立 TaskCompletionSource<TResult>

TaskCompletionSource<TResult>(Object)

使用指定的狀態,建立 TaskCompletionSource<TResult>

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

使用指定的狀態和選項,建立 TaskCompletionSource<TResult>

TaskCompletionSource<TResult>(TaskCreationOptions)

使用指定的選項,建立 TaskCompletionSource<TResult>

屬性

Task

取得這個 Task<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 狀態,並將它與例外狀況物件集合繫結。

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 狀態,並將其與例外狀況物件集合繫結。

TrySetResult(TResult)

嘗試將基礎 Task<TResult> 轉換為 RanToCompletion 狀態。

適用於

執行緒安全性

的所有成員 TaskCompletionSource<TResult> 都是安全線程,而且可以從多個執行緒同時使用。

另請參閱