【问题标题】:Why does coroutineScope block the process?为什么 coroutineScope 会阻塞进程?
【发布时间】: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 是与您的问题相关的帖子。
  • 感谢您分享链接。您分享的链接中的描述非常清楚。

标签: kotlin kotlin-coroutines


【解决方案1】:

coroutineScope 暂停了 CoroutineScope 作用域,所以“println("Coroutine scope is over") 行将在前一个 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)
}}

【讨论】:

  • 感谢您的回答!我能理解!
猜你喜欢
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2021-10-19
  • 2011-07-04
相关资源
最近更新 更多