TaskCompletionSource<TResult> Klasa

Definicja

Reprezentuje stronę producenta bez ruchu przychodzącego Task<TResult> do delegata, zapewniając dostęp do strony konsumenta za pośrednictwem Task właściwości.

generic <typename TResult>
public ref class TaskCompletionSource
public class TaskCompletionSource<TResult>
type TaskCompletionSource<'Result> = class
Public Class TaskCompletionSource(Of TResult)

Parametry typu

TResult

Typ wartości wyniku skojarzonej z tą TaskCompletionSource<TResult>wartością .

Dziedziczenie
TaskCompletionSource<TResult>

Przykłady

W poniższym przykładzie pokazano, jak używać elementu 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

Uwagi

W wielu scenariuszach warto włączyć Task<TResult> funkcję reprezentowania zewnętrznej operacji asynchronicznej. TaskCompletionSource<TResult> jest przeznaczony do tego celu. Umożliwia tworzenie zadania, które można przekazać konsumentom. Użytkownicy mogą używać członków zadania w taki sam sposób, jak w każdym innym scenariuszu obsługującym zmienne składowe zadania. Jednak w przeciwieństwie do większości zadań stan zadania utworzonego przez zadanieCompletionSource jest kontrolowany jawnie przez metody w zadaniuCompletionSource. Umożliwia to propagację zewnętrznej operacji asynchronicznej do bazowego zadania. Separacja gwarantuje również, że użytkownicy nie będą mogli przenieść stanu bez dostępu do odpowiedniego elementu TaskCompletionSource. Aby uzyskać więcej informacji, zobacz wpis Nature of TaskCompletionSource<TResult> w blogu Programowanie równoległe za pomocą platformy .NET.

Przykłady rozszerzeń równoległych zawierają również przykłady używania polecenia TaskCompletionSource<TResult>.

Konstruktory

TaskCompletionSource<TResult>()

Tworzy element TaskCompletionSource<TResult>.

TaskCompletionSource<TResult>(Object)

Tworzy obiekt TaskCompletionSource<TResult> o określonym stanie.

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

Tworzy obiekt TaskCompletionSource<TResult> o określonym stanie i opcjach.

TaskCompletionSource<TResult>(TaskCreationOptions)

Tworzy obiekt TaskCompletionSource<TResult> z określonymi opcjami.

Właściwości

Task

Pobiera utworzony przez ten TaskCompletionSource<TResult>element Task<TResult> .

Metody

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
SetCanceled()

Przenosi element bazowy Task<TResult> do Canceled stanu.

SetCanceled(CancellationToken)

Przenosi element bazowy Task<TResult> do Canceled stanu przy użyciu określonego tokenu.

SetException(Exception)

Przenosi bazę danych Task<TResult> do Faulted stanu i wiąże ją z określonym wyjątkiem.

SetException(IEnumerable<Exception>)

Przenosi bazę Task<TResult> danych do Faulted stanu i wiąże z nią kolekcję obiektów wyjątków.

SetResult(TResult)

Przenosi element bazowy Task<TResult> do RanToCompletion stanu.

ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)
TrySetCanceled()

Podejmuje próbę przejścia bazowego Task<TResult> Canceled do stanu.

TrySetCanceled(CancellationToken)

Próbuje przenieść bazę danych Task<TResult> do Canceled stanu i umożliwia przechowywanie tokenu anulowania w anulowanym zadaniu.

TrySetException(Exception)

Próbuje przenieść element bazowy Task<TResult> do Faulted stanu i powiązać go z określonym wyjątkiem.

TrySetException(IEnumerable<Exception>)

Próbuje przenieść bazę danych Task<TResult> do Faulted stanu i powiązać z nią kolekcję obiektów wyjątków.

TrySetResult(TResult)

Próbuje przenieść element bazowy Task<TResult> do RanToCompletion stanu .

Dotyczy

Bezpieczeństwo wątkowe

Wszystkie elementy członkowskie są TaskCompletionSource<TResult> bezpieczne wątkowo i mogą być używane z wielu wątków jednocześnie.

Zobacz też