Is there a promise interface for the Task
class like jQuery's deferred's promise
method?

- 187,200
- 47
- 362
- 445
-
1Could you elaborate? I do not understand what you expect. – Emond Jan 20 '12 at 21:31
3 Answers
The TPL, and the Task class, are very different than jQuery's promise.
A Task
is actually effectively more like the original action. If you wanted to have something run when the task completed, you'd use a continuation on the Task. This would effectively look more like:
Task someTask = RunMethodAsync();
someTask.ContinueWith( t =>
{
// This runs after the task completes, similar to how promise() would work
});
If you want to continue on multiple tasks, you can use Task.Factory.
ContinueWhenAll
or Task.Factory.
ContinueWhenAny
to make continuations that works on multiple tasks.

- 554,122
- 78
- 1,158
- 1,373
It seems like you're looking for TaskCompletionSource:
var tcs = new TaskCompletionSource<Args>();
var obj = new SomeApi();
// will get raised, when the work is done
obj.Done += (args) =>
{
// this will notify the caller
// of the SomeApiWrapper that
// the task just completed
tcs.SetResult(args);
}
// start the work
obj.Do();
return tcs.Task;
The code is taken from here: When should TaskCompletionSource<T> be used?

- 1
- 1

- 79
- 1
- 4
That sounds like a continuation, so use .ContinueWith(callback)
; or in C# 5.0, simply await
, i.e.
var task = /*...*/
var result = await task;
// everything here happens later on, when it is completed
// (assuming it isn't already)
different API, but I think it does what you are asking (a little hard to be sure... I'm not entirely sure I understand the question)

- 1,026,079
- 266
- 2,566
- 2,900