首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么coroutineScope会阻止该进程?

为什么coroutineScope会阻止该进程?
EN

Stack Overflow用户
提问于 2021-03-12 11:09:45
回答 1查看 74关注 0票数 1

this official documentation中,它说coroutineScope只是挂起,释放底层线程以用于其他用途。

但在示例代码中,它看起来会阻塞下一个进程,因为在coroutineScope中完成代码块之前不会执行println("Coroutine scope is over")

代码语言:javascript
复制
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会阻塞线程?

EN

回答 1

Stack Overflow用户

发布于 2021-03-12 11:22:37

coroutineScope挂起了CoroutineScope作用域,因此“println(”协程作用域已结束“)”行将在前一个coroutineScope完成后执行。您可以看到coroutineScope函数的代码:

代码语言:javascript
复制
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)
}}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66593629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档