TaskCompletionSource<TResult> Classe

Definizione

Rappresenta il lato producer di un oggetto Task<TResult> non associato a un delegato, fornendo l'accesso al lato consumer tramite la proprietà Task.

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

Parametri di tipo

TResult

Tipo del valore del risultato associato all'oggetto TaskCompletionSource<TResult>.

Ereditarietà
TaskCompletionSource<TResult>

Esempio

Nell'esempio seguente viene illustrato come usare un oggetto 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

Commenti

In molti scenari è utile abilitare un Task<TResult> per rappresentare un'operazione asincrona esterna. TaskCompletionSource<TResult> viene fornito a questo scopo. Consente la creazione di un'attività che può essere distribuita ai consumer. I consumer possono usare i membri dell'attività come in qualsiasi altro scenario che gestisce le variabili membro dell'attività. Tuttavia, a differenza della maggior parte delle attività, lo stato di un'attività creata da TaskCompletionSource viene controllato in modo esplicito dai metodi in TaskCompletionSource. Ciò consente di propagare il completamento dell'operazione asincrona esterna all'attività sottostante. La separazione garantisce inoltre che i consumer non siano in grado di eseguire la transizione dello stato senza accedere all'oggetto TaskCompletionSource corrispondente. Per altre informazioni, vedere la voce The Nature of TaskCompletionSource (Natura di TaskCompletionSource<TResult> ) nel blog Di programmazione parallela con .NET.

Gli esempi di estensioni parallele contengono anche esempi di come usare TaskCompletionSource<TResult>.

Costruttori

TaskCompletionSource<TResult>()

Crea un oggetto TaskCompletionSource<TResult>.

TaskCompletionSource<TResult>(Object)

Crea un oggetto TaskCompletionSource<TResult> con lo stato specificato.

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

Crea un oggetto TaskCompletionSource<TResult> con lo stato e le opzioni specificate.

TaskCompletionSource<TResult>(TaskCreationOptions)

Crea un oggetto TaskCompletionSource<TResult> con le opzioni specificate.

Proprietà

Task

Ottiene l'oggetto Task<TResult> creato da questo oggetto TaskCompletionSource<TResult>.

Metodi

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
SetCanceled()

Esegue la transizione dell'oggetto Task<TResult> sottostante allo stato Canceled.

SetCanceled(CancellationToken)

Esegue la transizione dell'oggetto Task<TResult> sottostante allo stato Canceled tramite il token specificato.

SetException(Exception)

Esegue la transizione dell'oggetto Task<TResult> sottostante allo stato Faulted e associa questo oggetto a un'eccezione specificata.

SetException(IEnumerable<Exception>)

Esegue la transizione dell'oggetto Task<TResult> sottostante allo stato Faulted e associa all'oggetto una raccolta di eccezioni.

SetResult(TResult)

Esegue la transizione dell'oggetto Task<TResult> sottostante allo stato RanToCompletion.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
TrySetCanceled()

Tenta di eseguire la transizione dell'oggetto Task<TResult> sottostante allo stato Canceled.

TrySetCanceled(CancellationToken)

Tenta di eseguire la transizione dell'oggetto Task<TResult> sottostante allo stato Canceled e abilita l'archiviazione di un token di annullamento nell'attività annullata.

TrySetException(Exception)

Tenta di eseguire la transizione dell'oggetto Task<TResult> sottostante allo stato Faulted e associa tale oggetto a un'eccezione specificata.

TrySetException(IEnumerable<Exception>)

Tenta di eseguire la transizione dell'oggetto Task<TResult> sottostante allo stato Faulted e associa a questo oggetto una raccolta di eccezioni.

TrySetResult(TResult)

Tenta di eseguire la transizione dell'oggetto Task<TResult> sottostante allo stato RanToCompletion.

Si applica a

Thread safety

Tutti i membri di TaskCompletionSource<TResult> sono thread-safe e possono essere usati da più thread contemporaneamente.

Vedi anche