共用方式為


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

取得這個 TaskCompletionSource<TResult>所建立的 Task<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 狀態。

適用於

執行緒安全性

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

另請參閱