Is prevTask.Wait() recommended to be used with Con

2019-01-16 06:53发布

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");
    });
}

7条回答
来,给爷笑一个
2楼-- · 2019-01-16 07:43

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.

查看更多
登录 后发表回答