Is there a promise interface for the Task class like jQuery's deferred's promise method?
- 181,601
- 45
- 354
- 430
-
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.
- 539,124
- 75
- 1,126
- 1,354
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)
- 976,458
- 251
- 2,474
- 2,830