Task.ContinueWith() vs 2 Tasks?

微笑、不失礼 提交于 2020-02-25 06:53:51

问题


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.



来源:https://stackoverflow.com/questions/15322057/task-continuewith-vs-2-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!