The Task Parallel Library is centered around the Task class and its derived Task<TResult>. The main purpose of these types is to represent the execution of an asynchronous workload and to provide an object with a means to operate on that workload, whether it be to wait for it, to continue from it, or the like. The primary type of asynchronous workload supported by Task is the execution of a delegate, either an Action or a Func<T>, such that the delegate’s execution in the underlying scheduler is represented by the Task. But in any compositional system that wants to use Task as its centerpiece, just support for asynchronous delegate execution isn’t enough: support must be provided for other asynchronous operations as well. For example, there are a variety of asynchronous operations already implemented in the .NET Framework and exposed through the Asynchronous Programming Model (APM) pattern or the Event-Based Asynchronous Pattern (EAP). In both of these cases, we’d like to be able to refer to these asynchronous operations as Tasks and operate on them as Tasks, even though the underlying work isn’t necessarily being performed by scheduling and executing a delegate. (More to come on both of those in future posts.)
To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource<TResult>.
The TaskCompletionSource<TResult> type serves two related purposes, both alluded to by its name: it is a source for creating a task, and the source for that task’s completion. In essence, a TaskCompletionSource<TResult> acts as the producer for a Task<TResult> and its completion. You create a TaskCompletionSource<TResult> and hand the underlying Task<TResult> it’s created, accessible from its Task property. Unlike Tasks created by Task.Factory.StartNew, the Task handed out by TaskCompletionSource<TResult> does not have any scheduled delegate associated with it. Rather, TaskCompletionSource<TResult> provides methods that allow you as the developer to control the lifetime and completion of the associated Task. This includes SetResult, SetException, and SetCanceled, as well as TrySet* variants of each of those. (A Task may only be completed once, thus attempting to set a Task into a completed state when it’s already in a completed state is an error, and the Set* methods will throw. However, as we’re dealing with concurrency here, and there are some situations where races may be expected between multiple threads trying to resolve the completion source, the TrySet* variants return Booleans indicating success rather than throwing an exceptions.)
As a simple example, imagine for a moment that you didn’t have Task.Factory.StartNew, and thus you needed a way to execute a Func<T> asynchronously and have a Task<T> to represent that operation. This could be done with a TaskCompletionSource<T> as follows:
public static Task<T> RunAsync<T>(Func<T> function)
{
if (function == null) throw new ArgumentNullException(“function”);
var tcs = new TaskCompletionSource<T>();
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
T result = function();
tcs.SetResult(result);
}
catch(Exception exc) { tcs.SetException(exc); }
});
return tcs.Task;
}
The operation is being performed asynchronously through a mechanism unknown to the TaskCompletionSource<T>. All it knows is that at some point, its SetResult or SetException method is being called to complete the Task<T> exposed through its Task property.
Note, too, that because Task<TResult> derives from Task, we can use the generic TaskCompletionSource<TResult> under the covers for methods that work in terms of Task rather than in terms of Task<TResult>. For example, consider the same RunAsync method just shown, but accepting an Action (which returns void) rather than a Func<T> (which returns T).
public static Task RunAsync(Action action)
{
var tcs = new TaskCompletionSource<Object>();
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
action();
tcs.SetResult(null);
}
catch(Exception exc) { tcs.SetException(exc); }
});
return tcs.Task;
}
Since we no longer care what the type of T is, I’ve defaulted to using Object. Then, when the Action is executed successfully, SetResult is still used to transition the Task into the RanToCompletion final state; however, since the actual result value is irrelevant, null is used. Finally, RunAsync returns Task rather than Task<Object>. Of course, the instantiated task’s type is still Task<Object>, but we need not refer to it as such, and the consumer of this method need not care about those implementation details.
In future posts, we’ll look at how TaskCompletionSource<TResult> is a staple in a developer’s toolbox, including the developers of the Task Parallel Library itself, where TaskCompletionSource<TResult> is used liberally internally.

PingBack from http://asp-net-hosting.simplynetdev.com/the-nature-of-taskcompletionsource-2/
PingBack from http://asp-net-hosting.simplynetdev.com/the-nature-of-taskcompletionsource/
The core entity in the Task Parallel Library around which everything else revolves is System.Threading.Tasks.Task. 
The Asynchronous Programming Model (APM) in the .NET Framework has been around since .NET 1.0 and is
PingBack from http://workfromhomecareer.info/story.php?id=22748
PingBack from http://www.vishwatech.com/globalnews/?p=1729
PingBack from http://cutebirdbaths.info/story.php?id=3554
As has been discussed previously, one of the new features in the Task Parallel Library is TaskCompletionSource<TResult>
A very good and interesting post that i have come across, thanks for sharing the post.
It's a useful paper. Thank you for it.
Really good article. Purpose of TaskCompletionSouce is explained very well. Thanks for such a nice explaination.
Short and concise, thanks a lot!
Hello Stephen,
I understand this article is quite old, but I take it TaskCompletionSource's use is only now multifold with async. However, its the same that's the problem – There seems to be numerous allocations of new Tcs. Unfortunately, its not a classes that can be reused once its result has been set. Is there any way to pool them and resuse them? I'd curious to understand what your recommendation would be for such scenarios.
@Prasanna V. Loganathar: There is no way to reuse a TaskCompletionSource; once a Task has transitioned to a completed state, it will always be in the completed state. You can cache completed tasks, and hand them out if that makes sense, on fast paths to avoid needing to create new ones. In some situations, you might also be able to use an AsyncTaskMethodBuilder directly; it's a struct that's similar to a TaskCompletionSource, but with a few behavioral differences, e.g. it only exposes SetResult and SetException methods, and it's canceled by passing an OperationCanceledException to SetException. This type is really meant to be used by the compiler, but it's exposed publicly. It's the type that backs async methods.
Ah. Thanks a lot. AsyncMethodBuilder seems to be perfect for my scenario.
PS: I don't think caching tasks really suits in this scenario, since it just doesn't signify completion. It has to propagate the exceptions as well. (The scenario actually here: github.com/…/QueuedStateMachine.cs => Tasks are queued up by a method, and the method returns a task immediately, but get completed only when the inner tasks are completed, with exception propagation. )
Was just looking at the source of AsyncMethodBuilder. Isn't there a race condition on the private Task when SetResult and Task property at the same time?
I'm going to guess that it that race condition was ignored on account of it being a struct. Which makes AsyncMethodBuilder unusable for wrapping it into a closure, while exposing the Task outside.
Thanks for the info on AsyncMethodBuilder though! I guess it scenarios where its access is controlled properly.
It's not ignored per se. As I mentioned, this type is meant to be used by the compiler, which ensures that Task is accessed before anyone could possibly call Set*.