TaskCompletionSource<TResult> TaskCompletionSource<TResult> TaskCompletionSource<TResult> TaskCompletionSource<TResult> Class

Definition

Stellt die Producerseite eines Task<TResult>-Objekts dar, dessen Bindung an einen Delegaten aufgehoben wurde. Das Element ermöglicht mithilfe der Task-Eigenschaft den Zugriff auf die Consumerseite.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)

Typparameter

TResult

Der Typ des Ergebniswerts zugeordneten TaskCompletionSource<TResult>.The type of the result value associated with this TaskCompletionSource<TResult>.

Vererbung
TaskCompletionSource<TResult>TaskCompletionSource<TResult>TaskCompletionSource<TResult>TaskCompletionSource<TResult>

Beispiele

Das folgende Beispiel zeigt, wie Sie mit einem 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

Hinweise

In vielen Szenarien ist es eignet sich zum Aktivieren einer Task<TResult> einen externen asynchronen Vorgang darstellen.In many scenarios, it is useful to enable a Task<TResult> to represent an external asynchronous operation. TaskCompletionSource<TResult> wird für diesen Zweck bereitgestellt.TaskCompletionSource<TResult> is provided for this purpose. Dadurch wird die Erstellung einer Aufgabe, die an Consumer übergeben werden kann.It enables the creation of a task that can be handed out to consumers. Die Kunden können die Elemente der Aufgabe die gleiche Weise verwenden, wie in allen anderen Szenarien, die Verarbeitung von Task-Membervariablen.The consumers can use the members of the task the same way as they would in any other scenario handling task member variables. Im Gegensatz zu den meisten Aufgaben der Status einer Aufgabe, die von einer TaskCompletionSource erstellt jedoch explizit durch die Methoden für TaskCompletionSource gesteuert.However, unlike most tasks, the state of a task created by a TaskCompletionSource is controlled explicitly by the methods on TaskCompletionSource. Dies ermöglicht den Abschluss des asynchronen Vorgangs externen an die zugrunde liegende Aufgabe weitergegeben werden.This enables the completion of the external asynchronous operation to be propagated to the underlying Task. Die Trennung sichergestellt, dass Kunden nicht den Zustand ohne Zugriff auf die entsprechende TaskCompletionSource wechseln können.The separation also ensures that consumers are not able to transition the state without access to the corresponding TaskCompletionSource. Weitere Informationen finden Sie im Eintrag die Art der TaskCompletionSource<TResult > im zur parallelen Programmierung mit .NET Blog.For more information, see the entry The Nature of TaskCompletionSource<TResult> in the Parallel Programming with .NET blog.

Die Parallel Extensions Samples auch enthalten Beispiele zur Verwendung von TaskCompletionSource<TResult>.The Parallel Extensions samples also contain examples of how to use TaskCompletionSource<TResult>.

Konstruktoren

TaskCompletionSource<TResult>() TaskCompletionSource<TResult>() TaskCompletionSource<TResult>() TaskCompletionSource<TResult>()

Erstellt eine TaskCompletionSource<TResult>.Creates a TaskCompletionSource<TResult>.

TaskCompletionSource<TResult>(Object) TaskCompletionSource<TResult>(Object) TaskCompletionSource<TResult>(Object) TaskCompletionSource<TResult>(Object)

Erstellt ein TaskCompletionSource<TResult>-Objekt mit dem angegebenen Zustand.Creates a TaskCompletionSource<TResult> with the specified state.

TaskCompletionSource<TResult>(Object, TaskCreationOptions) TaskCompletionSource<TResult>(Object, TaskCreationOptions) TaskCompletionSource<TResult>(Object, TaskCreationOptions) TaskCompletionSource<TResult>(Object, TaskCreationOptions)

Erstellt ein TaskCompletionSource<TResult>-Objekt mit dem angegebenen Zustand und den angegebenen Optionen.Creates a TaskCompletionSource<TResult> with the specified state and options.

TaskCompletionSource<TResult>(TaskCreationOptions) TaskCompletionSource<TResult>(TaskCreationOptions) TaskCompletionSource<TResult>(TaskCreationOptions) TaskCompletionSource<TResult>(TaskCreationOptions)

Erstellt ein TaskCompletionSource<TResult>-Objekt mit den angegebenen Optionen.Creates a TaskCompletionSource<TResult> with the specified options.

Eigenschaften

Task Task Task Task

Ruft den von der Task<TResult> erstellten TaskCompletionSource<TResult> ab.Gets the Task<TResult> created by this TaskCompletionSource<TResult>.

Methoden

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Bestimmt, ob das angegebene Objekt mit dem aktuellen Objekt identisch ist.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Fungiert als Standardhashfunktion.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Ruft den Type der aktuellen Instanz ab.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.Creates a shallow copy of the current Object.

(Inherited from Object)
SetCanceled() SetCanceled() SetCanceled() SetCanceled()

Sorgt für den Übergang des zugrunde liegenden Task<TResult>-Objekts in den Canceled-Zustand.Transitions the underlying Task<TResult> into the Canceled state.

SetException(Exception) SetException(Exception) SetException(Exception) SetException(Exception)

Lässt den zugrunde liegenden Task<TResult> in den Faulted-Status übergehen und bindet ihn an eine angegebene Ausnahme.Transitions the underlying Task<TResult> into the Faulted state and binds it to a specified exception.

SetException(IEnumerable<Exception>) SetException(IEnumerable<Exception>) SetException(IEnumerable<Exception>) SetException(IEnumerable<Exception>)

Sorgt für den Übergang des zugrunde liegenden Task<TResult> in den Faulted-Status und bindet eine Sammlung von Ausnahmeobjekten daran.Transitions the underlying Task<TResult> into the Faulted state and binds a collection of exception objects to it.

SetResult(TResult) SetResult(TResult) SetResult(TResult) SetResult(TResult)

Sorgt für den Übergang des zugrunde liegenden Task<TResult>-Objekts in den RanToCompletion-Zustand.Transitions the underlying Task<TResult> into the RanToCompletion state.

ToString() ToString() ToString() ToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.Returns a string that represents the current object.

(Inherited from Object)
TrySetCanceled() TrySetCanceled() TrySetCanceled() TrySetCanceled()

Versucht, den Übergang des zugrunde liegenden Task<TResult>-Objekts in den Canceled-Zustand auszuführen.Attempts to transition the underlying Task<TResult> into the Canceled state.

TrySetCanceled(CancellationToken) TrySetCanceled(CancellationToken) TrySetCanceled(CancellationToken) TrySetCanceled(CancellationToken)

Versucht, den Übergang des zugrunde liegenden Task<TResult>-Objekts in den Canceled-Zustand auszuführen, und ermöglicht das Speichern eines Abbruchtokens in der abgebrochenen Aufgabe.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) TrySetException(Exception) TrySetException(Exception) TrySetException(Exception)

Versucht den Übergang der zugrunde liegenden Task<TResult> in den Faulted-Status und bindet sie an eine angegebene Ausnahme.Attempts to transition the underlying Task<TResult> into the Faulted state and binds it to a specified exception.

TrySetException(IEnumerable<Exception>) TrySetException(IEnumerable<Exception>) TrySetException(IEnumerable<Exception>) TrySetException(IEnumerable<Exception>)

Versucht den Übergang der zugrunde liegenden Task<TResult> in den Faulted-Status und bindet eine Sammlung von Ausnahmeobjekten daran.Attempts to transition the underlying Task<TResult> into the Faulted state and binds a collection of exception objects to it.

TrySetResult(TResult) TrySetResult(TResult) TrySetResult(TResult) TrySetResult(TResult)

Versucht, den Übergang des zugrunde liegenden Task<TResult>-Objekts in den RanToCompletion-Zustand auszuführen.Attempts to transition the underlying Task<TResult> into the RanToCompletion state.

Gilt für:

Threadsicherheit

Alle Mitglieder der TaskCompletionSource<TResult> sind threadsicher und können von mehreren Threads gleichzeitig verwendet werden.All members of TaskCompletionSource<TResult> are thread-safe and may be used from multiple threads concurrently.

Siehe auch