kotlin中两个协程启动的区别

Differences between two coroutine launch in kotlin

CoroutineScope(dispatchers).launch{}coroutineScope{ launch{}}有什么区别?

假设我有以下代码:

(你可以去 Kotlin 游乐场 运行 这个片段 https://pl.kotl.in/U4eDY4uJt

suspend fun perform(invokeAfterDelay: suspend () -> Unit) {
    // not printing
    CoroutineScope(Dispatchers.Default).launch {
        delay(1000)
        invokeAfterDelay()
    }


    // will print
    coroutineScope {
        launch {
            delay(1000)
            invokeAfterDelay()
        }
    }
}

fun printSomething() {
    println("Counter")
}


fun main() {
    runBlocking {
        perform {
            printSomething()
        }
    }

}

正如评论所述,当使用 CoroutineScope().launch 时,它不会调用打印,但是当使用其他方式时,代码会按预期运行。

有什么区别?

谢谢。

进一步的问题

新发现。

如果我像这样离开 perform 函数(不注释掉其中一个协程)

suspend fun perform(invokeAfterDelay: suspend () -> Unit) {

        CoroutineScope(Dispatchers.Default).launch {
            delay(1000)
            invokeAfterDelay()
        }

        coroutineScope {
            launch {
                delay(1000)
                invokeAfterDelay()
            }
        }

    }

那么这两个协程都会被执行 为什么?

CoroutineScope().launch {}coroutineScope { launch{} } 几乎没有共同点。前者只是为 launch 到 运行 设置一个临时作用域,立即完成,后者是一个可挂起的函数,确保在它 returns 之前启动的所有协同程序完成.

您 "Further question" 下的代码段与原始代码段相同,只是删除了评论。

第一个协程是否打印任何东西取决于非确定性行为:虽然 performcoroutineScope 内花费时间,等待内部 launched 的完成协程,第一个可能会或可能不会完成自己。他们有相同的延迟。