但是在示例代码中,它看起来会阻塞下一个进程,因为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
}
我知道runBlock会等到它的所有子级完成。所以在我的理解中,runBlock应该在执行println("Coroutine scope is over")
行后等待coroutineScope完成。
为什么在这个例子中coroutineScope会阻塞线程?
CoroutineScope挂起了CoroutineScope作用域,因此“println("Coroutine scope is over")”行将在上一个协程作用域完成后执行。你可以看到协程作用域的代码:
public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return suspendCoroutineUninterceptedOrReturn { uCont ->
val coroutine = ScopeCoroutine(uCont.context, uCont)
coroutine.startUndispatchedOrReturn(coroutine, block)
}}