Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I start a continuation task instance?

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?

like image 939
gigi Avatar asked Mar 14 '12 16:03

gigi


People also ask

What is a continuation task?

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.

What is the difference between task run and task factory StartNew?

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!

What is ContinueWith C#?

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.

What is task factory StartNew?

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.


1 Answers

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.

like image 107
usr Avatar answered Sep 22 '22 15:09

usr