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 に関連付けられている結果値の型-0。The type of the result value associated with this TaskCompletionSource<TResult>.

継承
TaskCompletionSource<TResult>

次の例では、@no__t 0 を使用する方法を示します。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. ただし、ほとんどのタスクとは異なり、Taskのソースによって作成されたタスクの状態は、Taskて Source のメソッドによって明示的に制御されます。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. また、分離によって、コンシューマーは、対応する Taskable ソースにアクセスせずに状態を遷移させることができなくなります。The separation also ensures that consumers are not able to transition the state without access to the corresponding TaskCompletionSource. 詳細については、.NET の並列プログラミングに関するブログの「 taskno__t source @-1TResult tresult の特性」を参照してください。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()

現在のインスタンスの Type を取得します。Gets 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()

現在のオブジェクトを表す文字列を返します。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 0 のすべてのメンバーはスレッドセーフであり、複数のスレッドから同時に使用することができます。All members of TaskCompletionSource<TResult> are thread-safe and may be used from multiple threads concurrently.

こちらもご覧ください