Is there a promise interface for the Task
class like jQuery's deferred's promise
method?
As a reminder, Promise Tasks are tasks that represent a kind of “event” within a system; they don’t have any user-defined code to execute. Task.Delay is the asynchronous equivalent of Thread.Sleep.
The Task class represents a single operation that does not return a value and that usually executes asynchronously. Task objects are one of the central components of the task-based asynchronous pattern first introduced in the.NET Framework 4.
Beginning with C# 8.0, an interface may define a default implementation for members. It may also define static members in order to provide a single implementation for common functionality. In the following example, class ImplementationClass must implement a method named SampleMethod that has no parameters and returns void.
If you're using .NET 4.0, you can use TaskCompletionSource<T>: Ultimately, if theres nothing asynchronous about your method you should consider exposing a synchronous endpoint ( CreateBar) which creates a new Bar. That way there's no surprises and no need to wrap with a redundant Task.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With