简体   繁体   English

Task.ContinueWith()vs 2任务?

[英]Task.ContinueWith() vs 2 Tasks?

When should I use 我什么时候应该使用

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

vs VS

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

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. 一个例子是添加另一个var task3 = task1.ContinueWith()因此任务二和三将同时执行,但只有在第一个任务完成处理时才会执行。 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 . 注意我将task1替换为task2 Starting either Task will cause task1 to start first. 启动任务将导致task1首先启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM