Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 4.0's Task class - Promise interface?

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

like image 862
Daniel A. White Avatar asked Jan 20 '12 21:01

Daniel A. White


People also ask

What are promise tasks in JavaScript?

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.

What is a task class in Java?

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.

What is the default implementation of an interface member?

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.

Is there a way to wrap taskcompletionsource in a task?

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.


2 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.

like image 76
Reed Copsey Avatar answered Sep 19 '22 12:09

Reed Copsey


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?

like image 24
Dmitry Egorov Avatar answered Sep 20 '22 12:09

Dmitry Egorov