Task.ContinueWith() vs 2 Tasks?

2019-08-08 18:40发布

问题:

When should I use

Task task1 = Task.Factory.StartNew (() => {...})
                 .ContinueWith (ant => Console.Write ("2"));

vs

Task task1 = Task.Factory.StartNew (() => {... });
Task task2 = task1.ContinueWith (ant => Console.Write ("2"));

回答1:

It means the same, except for you'll have a reference to the second task now. You can use the second option if the first task needs some processing before executing the tasks all together. An example is to add another var task3 = task1.ContinueWith() so task two and three will execute concurrently, but only if the first task is done processing. Actually it should be:

Task task2 = Task.Factory.StartNew (() => {...}).ContinueWith (ant => Console.Write ("2"));

Task task1 = Task.Factory.StartNew (() => {... });
Task task2 = task1.ContinueWith (ant => Console.Write ("2"));

Note I replaced task1 to task2. Starting either Task will cause task1 to start first.