Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is prevTask.Wait() recommended to be used with ContinueWith (from the Tasks library)?

So I was told recently that how I was using my .ContinueWith for Tasks was not the proper way to use them. I have yet to find evidence of this on the internet so I will ask you guys and see what the answer is. Here is an example of how I use .ContinueWith:

public Task DoSomething()
{
    return Task.Factory.StartNew(() =>
    {
        Console.WriteLine("Step 1");
    })
    .ContinueWith((prevTask) =>
    {
        Console.WriteLine("Step 2");
    })
    .ContinueWith((prevTask) =>
    {
        Console.WriteLine("Step 3");
    });
}

Now I know this is a simple example and it will run very fast, but just assume each task does some longer operation. So, what I was told is that in the .ContinueWith, you need to say prevTask.Wait(); otherwise you could do work before the previous task finishes. Is that even possible? I assumed my second & third task would only run once their previous task finishes.

What I was told how to write the code:

public Task DoSomething()
{
    return Task.Factory.StartNew(() =>
    {
        Console.WriteLine("Step 1");
    })
    .ContinueWith((prevTask) =>
    {
        prevTask.Wait();
        Console.WriteLine("Step 2");
    })
    .ContinueWith((prevTask) =>
    {
        prevTask.Wait();
        Console.WriteLine("Step 3");
    });
}
like image 786
Travyguy9 Avatar asked Aug 10 '12 15:08

Travyguy9


People also ask

When should I use task ContinueWith?

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 a continuation Task C#?

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.


2 Answers

Ehhh.... I think some of the current answers are missing something: what happens with exceptions?

The only reason you would call Wait in a continuation would be to observe a potential exception from the antecedent in the continuation itself. The same observation would happen if you accessed Result in the case of a Task<T> and also if you manually accessed the Exception property. Frankly, I wouldn't call Wait or access Result because if there is an exception you'll pay the price of re-raising it which is unnecessary overhead. Instead you can just check the IsFaulted property off the antecedent Task. Alternatively you can create forked workflows by chaining on multiple sibling continuations that only fire based on either success or failure with TaskContinuationOptions.OnlyOnRanToCompletion and TaskContinuationOptions.OnlyOnFaulted.

Now, it's not necessary to observe the exception of the antecedent in the continuation, but you may not want your workflow to move forward if, say, "Step 1" failed. In that case: specifying TaskContinuationOptions.NotOnFaulted to your ContinueWith calls would prevent the continuation logic from ever even firing.

Keep in mind that, if your own continuations don't observe the exception, the person who is waiting on this overall workflow to complete is going to be the one to observe it. Either they're Waiting on the Task upstream or have tacked on their own continuation to know when it is complete. If it is the latter, their continuation would need to use the aforementioned observation logic.

like image 153
Drew Marsh Avatar answered Oct 18 '22 19:10

Drew Marsh


You are using it correctly.

Creates a continuation that executes asynchronously when the target Task completes.

Source: Task.ContinueWith Method (Action as MSDN)

Having to call prevTask.Wait() in every Task.ContinueWith invocation seems like a weird way to repeat unnecessary logic - i.e. doing something to be "super duper sure" because you actually don't understand what a certain bit of code does. Like checking for a null just to throw an ArgumentNullException where it would've been thrown anyway.

So, no, whoever told you that is wrong and probably doesn't understand why Task.ContinueWith exists.

like image 20
Anders Arpi Avatar answered Oct 18 '22 19:10

Anders Arpi