首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解runBlocking和coroutineScope的行为差异

理解runBlocking和coroutineScope的行为差异
EN

Stack Overflow用户
提问于 2021-02-27 15:18:49
回答 2查看 411关注 0票数 1

在Kotlin指南这里中,当解释runBlockingcoroutineScope之间的区别时,它说:

..。主要的区别是runBlocking方法阻塞当前线程等待,而coroutineScope只是挂起,释放底层线程用于其他用途。..。

这是可以理解的但是,在这里列出的示例代码中:

代码语言: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
}

它产生以下输出:

代码语言:javascript
复制
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over

coroutineScope替换为runBlocking

代码语言:javascript
复制
import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    launch { 
        delay(200L)
        println("Task from runBlocking")
    }
    
    runBlocking { // instead of coroutineScope, previously
        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将阻塞直到它的块完成,包括所有子协同:

代码语言:javascript
复制
Task from coroutine scope
Task from nested launch
Task from runBlocking
Coroutine scope is over

有人能解释一下这种行为吗?我在这里监督什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-27 15:44:07

在runBlocking中拥有runBlocking是..。不寻常。更常见的是,runBlocking仅仅是一种外在的东西。实际上,runBlocking的实现将使用外部runBlocking的事件循环,而不是创建新的事件循环,因此在这种情况下,它实际上就像coroutineScope一样。

来源:https://github.com/Kotlin/kotlinx.coroutines/blob/dda99e21f45f65eb540ccf4d5e82faf7559bc9e5/kotlinx-coroutines-core/jvm/src/Builders.kt#L46

票数 3
EN

Stack Overflow用户

发布于 2021-02-27 15:28:22

runBlocking只阻塞当前线程,直到block返回为止。它不影响block的执行方式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66400241

复制
相关文章

相似问题

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