Task.ContinueWith()对2的任务?任务、Task、ContinueWith

2023-09-07 16:23:49 作者:微凉徒眸意浅挚半

当我应该用

 工作任务1 = Task.Factory.StartNew(()=> {...})
                 .ContinueWith(蚂蚁=> Console.Write(2));
 

VS

 工作任务1 = Task.Factory.StartNew(()=> {...});
任务任务2 = task1.ContinueWith(蚂蚁=> Console.Write(2));
 
UFLO 4 如何发起一个指定任务TaskType.Appoint

解决方案

它的意思是相同的,除了你就会有一个关于第二个任务吧。如果第一个任务需要一定的处理执行的任务都在一起才可以使用第二个选项。一个例子是添加另一个 VAR任务3 = task1.ContinueWith()这样的任务二,三将同时执行,但只有第一个任务做处理。其实这应该是:

 任务TASK2 = Task.Factory.StartNew(()=> {...})ContinueWith。(蚂蚁=> Console.Write(2));

任务任务1 = Task.Factory.StartNew(()=> {...});
任务任务2 = task1.ContinueWith(蚂蚁=> Console.Write(2));
 

请注意我替换任务1 TASK2 。无论是启动任务将导致任务1 率先启动。

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

解决方案

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.