TaskCompletionSource(TResult) Class (System.Threading.Tasks)

Switch View :
ScriptFree
.NET Framework Class Library
TaskCompletionSource<TResult> Class

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

Represents the producer side of a System.Threading.Tasks.Task{TResult} unbound to a delegate, providing access to the consumer side through the Task property.

Inheritance Hierarchy

System.Object
  System.Threading.Tasks.TaskCompletionSource<TResult>

Namespace:  System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
	ExternalThreading := True)> _
Public Class TaskCompletionSource(Of TResult)
C#
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class TaskCompletionSource<TResult>

Visual C++
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
generic<typename TResult>
public ref class TaskCompletionSource
F#
[<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    ExternalThreading = true)>]
type TaskCompletionSource<'TResult> =  class end

Type Parameters

TResult

The type of the result value assocatied with this TaskCompletionSource<TResult>.

The TaskCompletionSource<TResult> type exposes the following members.

Constructors

  Name Description
Public method TaskCompletionSource<TResult>() Creates a TaskCompletionSource<TResult>.
Public method TaskCompletionSource<TResult>(Object) Creates a TaskCompletionSource<TResult> with the specified state.
Public method TaskCompletionSource<TResult>(TaskCreationOptions) Creates a TaskCompletionSource<TResult> with the specified options.
Public method TaskCompletionSource<TResult>(Object, TaskCreationOptions) Creates a TaskCompletionSource<TResult> with the specified state and options.
Top
Properties

  Name Description
Public property Task Gets the System.Threading.Tasks.Task{TResult} created by this TaskCompletionSource<TResult>.
Top
Methods

  Name Description
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method SetCanceled Transitions the underlying System.Threading.Tasks.Task{TResult} into the Canceled state.
Public method SetException(IEnumerable<Exception>) Transitions the underlying System.Threading.Tasks.Task{TResult} into the Faulted state.
Public method SetException(Exception) Transitions the underlying System.Threading.Tasks.Task{TResult} into the Faulted state.
Public method SetResult Transitions the underlying System.Threading.Tasks.Task{TResult} into the RanToCompletion state.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Public method TrySetCanceled Attempts to transition the underlying System.Threading.Tasks.Task{TResult} into the Canceled state.
Public method TrySetException(IEnumerable<Exception>) Attempts to transition the underlying System.Threading.Tasks.Task{TResult} into the Faulted state.
Public method TrySetException(Exception) Attempts to transition the underlying System.Threading.Tasks.Task{TResult} into the Faulted state.
Public method TrySetResult Attempts to transition the underlying System.Threading.Tasks.Task{TResult} into the RanToCompletion state.
Top
Remarks

In many scenarios, it is useful to enable a Task<TResult> to represent an external asynchronous operation. TaskCompletionSource<TResult> is provided for this purpose. It enables the creation of a task that can be handed out to consumers, and those consumers can use the members of the task as they would any other. 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. The separation also ensures that consumers are not able to transition the state without access to the corresponding TaskCompletionSource.

For more information, see TPL and Traditional .NET Asynchronous Programming

The Parallel Extensions samples also contain examples of how to use TaskCompletionSource<TResult>.

Note Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

Examples

The following example shows how to use a TaskCompletionSource<TResult>:

Visual Basic

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.
    ' Documentation:
    '   http://msdn.microsoft.com/en-us/library/dd449199(VS.100).aspx

    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


C#

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.
    // Documentation:
    //		http://msdn.microsoft.com/en-us/library/dd449199(VS.100).aspx
    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());
            }
        }
    }

}


Version Information

.NET Framework

Supported in: 4.5, 4

.NET Framework Client Profile

Supported in: 4
Platforms

Windows 8 Consumer Preview, Windows Server 8 Beta, Windows 7, Windows Server 2008 SP2, Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety

All members of TaskCompletionSource<TResult> are thread-safe and may be used from multiple threads concurrently.

See Also

Reference

Other Resources