在this official documentation中,它说coroutineScope只是挂起,释放底层线程以用于其他用途。
但在示例代码中,它看起来会阻塞下一个进程,因为在coroutineScope中完成代码块之前不会执行println("Coroutine scope is over")。
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会阻塞线程?
发布于 2021-03-12 11:22:37
coroutineScope挂起了CoroutineScope作用域,因此“println(”协程作用域已结束“)”行将在前一个coroutineScope完成后执行。您可以看到coroutineScope函数的代码:
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)
}}https://stackoverflow.com/questions/66593629
复制相似问题