【发布时间】:2021-06-10 02:25:16
【问题描述】:
在this official documentation 中,它说 coroutineScope 只是挂起,释放底层线程以供其他用途。
但在示例代码中,它看起来会阻塞下一个进程,因为 println("Coroutine scope is over") 直到完成 coroutineScope 中的代码块才会执行。
import kotlinx.coroutines.*
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
println("Task from runBlocking")
}
coroutineScope { // Creates a coroutine scope
launch {
delay(500L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // This line will be printed before the nested launch
}
println("Coroutine scope is over") // This line is not printed until the nested launch completes
}
我知道 runBlocking 会等到它的所有子进程完成。所以在我的理解中,runBlocking 应该在执行println("Coroutine scope is over") 行之后等待coroutineScope 完成。
为什么 coroutineScope 在这个例子中会阻塞线程?
【问题讨论】:
-
Here 是与您的问题相关的帖子。
-
感谢您分享链接。您分享的链接中的描述非常清楚。