孩子们应该如何在Kotlin公司工作?

孩子们应该如何在Kotlin公司工作?,kotlin,kotlinx.coroutines,Kotlin,Kotlinx.coroutines,根据文档cancelChildren应该取消协同程序的子项,但不影响父项(“此作业本身的状态不受影响”) val outer = launch { try { launch (coroutineContext) { try { // work here } catch (ex: Exception) { println("In inner catch")

根据文档cancelChildren应该取消协同程序的子项,但不影响父项(“此作业本身的状态不受影响”)

    val outer = launch {
    try {
        launch (coroutineContext) {
            try {
                // work here
            } catch (ex: Exception) {
                println("In inner catch")
            } finally {
                println("In inner finally")
            }
        }
        delay(5000) // so the outer job is running when I cancel it
    } catch (ex: CancellationException) {
        println("In outer catch")
    } finally {
        println("In outer finally")
    }
}

delay(100) // give it  a chance to run
outer.cancelChildren()
然后我看到了下面的内容

In inner catch
In inner finally
In outer catch
In outer finally
为什么“外部”工作会被取消

这与我调用outer.cancel(但我预期)时得到的行为完全相同。

您在外部协同程序中的
延迟(5000)
是可取消的,因此受
outer.cancelChildren()
的影响。它抛出外部
try
中的
CancellationException
cancelChildren
函数不会取消外部作业,调用后通过选中
outer.isCancelled
可以明显看出这一点

如果从代码中删除了
延迟
调用,它将打印预期结果。请注意,协同程序会等待其子女,因此不必延迟:

父协同程序总是等待其所有子进程的完成。父级不必显式跟踪它启动的所有子级,也不必使用Job.join在最后等待它们


谢谢,现在有道理了。挂起函数(延迟、加入…)会引发CancellationException,我没有意识到这一点。这是有道理的,因为“家长”应该知道“孩子”已被取消是的,确切地说:-)