kotlin - 协程作用域构建器流程如何工作
问题描述
科特林 说
- runBlocking 方法阻塞当前线程等待
- coroutineScope 只是挂起,释放底层线程以供其他用途。
- 因此 runBlocking 是一个常规函数,而 coroutineScope 是一个挂起函数
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 阻塞主线程
launch
并将执行,它涉及delay(200L)
- 于是,底层协程被释放运行
coroutineScope
,来到delay(500L)
&delay(100L)
- 所以,底层协程再次被释放,它应该打印
println("Coroutine scope is over")
。
这是我对runBlocking
和的理解coroutineScope
。这没有按预期工作。
输出是
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over
任何人都可以以一种简单的方式解释这一点。
解决方案
launch
导致块异步执行,因此调用launch
立即返回,协程继续运行,不等待启动块的执行。
因此,紧接在runBlocking
被调用之后,第一个和第二个launch
被一个接一个地调用,并且紧接着协程被挂起delay(100L)
。
100 毫秒后,协程恢复并打印“来自协程范围的任务”,然后嵌套协程范围的块的执行结束。协程作用域总是等待它启动的所有作业的执行结束,所以它在这里等待 500 毫秒。
同时执行了两个已启动的块,因此首先打印“Task from runBlocking”(距开始 200 毫秒后),然后打印“来自嵌套启动的任务”(距开始 500 毫秒后)。
最终,在内部启动的作业完成后,内部协程范围完成等待,外部协程继续并打印“协程范围结束”。
这就是故事。我希望它有助于理解代码是如何执行的,以及为什么打印的顺序是这样的。
推荐阅读
- php - php - 位掩码“解码”
- unit-testing - 笑话单元测试:阻止所有传出流量
- windows - 如何更改 Electron Builder 创建的应用程序快捷方式中的“开始”路径?
- sql-server - 使用隐藏表达式仅在 Tablix 中显示一行
- powershell - EXE 的自动检测静音开关
- user-interface - 圆特定角 SwiftUI
- python - 删除列中的重复值,但在 python 中为数据框保留第一个重复值
- php - 根据特定 id 插入多个字段值
- sql - 如何在 SQL 中使用动态函数来获得蛇模式?
- asp.net - ASP.Net 表单,如 wordpress 表单,用于添加新帖子