ContinueWith 和没有 ContinueWith 有什么区别?

What's the difference with ContinueWith and without?

我 运行 这两个版本,似乎每个版本都给我相同的输出,这是连续的。

ContinueWith_Method1a();
ContinueWith_Method1b();

Task.Run(() => ContinueWith_Method1a())
        .ContinueWith(task => ContinueWith_Method1b())
        .Wait();

我尝试了以下但出现此错误:

Cannot implicitly convert type 'void' to 'System.Threading.Tasks.Task'

Task t = Task.Run(() => ContinueWith_Method1a())
        .ContinueWith(task => ContinueWith_Method1b())
        .Wait();

static void ContinueWith_Method1a()
{
    System.Console.WriteLine("Continue With Method 1a started.");
    Thread.Sleep(1000);// Simulate task processing time.

    System.Console.WriteLine("Continue With Method 1a completed.");
}

static void ContinueWith_Method1b()
{
    System.Console.WriteLine("Continue With Method 1b started.");
    Thread.Sleep(1000);// Simulate task processing time.

    System.Console.WriteLine("Continue With Method 1b completed.");
}

ContinueWith 在第一个任务完成后开始下一个任务。 所以你的两个例子 运行 同步(第一个方法 A 然后方法 b)

编辑:

除了您的编辑之外,您的错误是由 .Wait() 函数引起的,该函数等待任务并且 returns 无效。

What's the difference with ContinueWith and without?

您 post 的标题问题非常具有误导性。在您的代码示例中使用 ContinueWith() 最少 有趣的区别。更重要的区别是第一个示例直接调用方法,而第二个示例使用 Task.Run().

现在,碰巧没有理由编写第二个示例中的代码。即使忽略 ContinueWith() 方面,如果您的所有任务所做的只是调用一个方法,并且您要对该任务做的所有事情都是同步等待任务(即调用 Wait() 方法),那么您也可以在当前线程中调用该方法。在那种情况下不需要 Task.Run()

同样,如果您要对 ContinueWith() 做的只是在之后立即调用另一个方法,您最好直接调用该方法。

通过在当前线程中阻塞,您已经使异步执行这两个方法可能具有的任何优势变得无用。

当然,有明显的机械区别。最终,您会得到相同的结果,但实现该结果的方式却大不相同。在第一个示例中,您只需一个接一个地调用方法。每个调用都在当前线程中执行。在第二个示例中,您实际上是在要求线程池按顺序执行每个方法,同时阻塞当前线程等待它发生。

这类似于你剥洋葱然后自己切,和让别人剥洋葱然后切,而你坐在那里摆弄你的拇指等待他们完成这些动作的区别。

最后,就您收到的错误消息而言,"Cannot implicitly convert type 'void' to 'System.Threading.Tasks.Task'",那只是因为您添加了 Task t 变量并尝试设置它Wait() 方法的结果。由于 Wait() 方法没有 return 任何东西(即声明的 return 类型为 void),更不用说 Task 的值了,这是不可能的使用其 return 值设置 t 的值。因此出现错误消息。如果你想分配一个 Task 变量,你只需要省略对 Wait():

的调用
Task t = Task.Run(() => ContinueWith_Method1a())
        .ContinueWith(task => ContinueWith_Method1b());