I have this method that Starts a Task and returns the last cahined Task to get the result:
public Task<double> GetTask()
{
return Task.Factory.StartNew((() => 10))
.ContinueWith(i =>
{
return i.Result + 2;
})
.ContinueWith(i =>
{
return (double)i.Result;
});
}
I would like to have the same method returning the same task but without starting it automatically with the Task.Factory.StartNew like this:
public Task<double> GetTask2()
{
return new Task<int>((() => 10))
.ContinueWith(i =>
{
return i.Result + 2;
})
.ContinueWith(i =>
{
return (double)i.Result;
});
}
Anyway I wasn't able to find a way to start the task returned by GetTask2 and get the result. How can I start it and get the result?
A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.
Task. Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!
The ContinueWith function is a method available on the task that allows executing code after the task has finished execution. In simple words it allows continuation. Things to note here is that ContinueWith also returns one Task. That means you can attach ContinueWith one task returned by this method.
StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.
Something like this:
public Task<double> GetTask()
{
var rootTask = new Task<int>((() => 10));
var continuationTask = rootTask
.ContinueWith(i =>
{
return i.Result + 2;
})
.ContinueWith(i =>
{
return (double)i.Result;
});
rootTask.Start(),
return continuationTask;
}
If you want to start the task only later, you can return both from your function.
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