gpt4 book ai didi

multithreading - Kotlin Supervisor Job 意外行为

转载 作者:行者123 更新时间:2023-12-02 12:46:11 24 4
gpt4 key购买 nike

我有下一个代码:

import kotlin.coroutines.*;
import kotlinx.coroutines.*;

val job = SupervisorJob()
val handler = CoroutineExceptionHandler { _, e ->
println("Catch: $e")
}
val coroutineContext: CoroutineContext = Dispatchers.IO + job + handler

fun main() {
val job1 = GlobalScope.launch(coroutineContext) {
// supervisorScope {
launch {
println("Test0")
for (i in 0..5) {
println("Working! Iteration: $i")
delay(1000)
}
println("Test0 end")
}


launch {
println("Test1")
delay(2000)
throw IllegalAccessException()
}

launch {
println("Test2")
delay(3000)
println("Test2 end")
}

}
//}
runBlocking { job1.join() }
println("Test3")
}

如您所见,我正在使用 SupervisorJob通过在 coroutineContext 中传递它进入 GlobalScope.launch避免在任何地方发生错误时取消任何子级,并且必须在 handler 中处理错误.文档接着说 SupervisorJob :
Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other.

基于此,我期待这样的事情:
Test0
Working! Iteration: 0
Test1
Test2
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Working! Iteration: 2
Working! Iteration: 3
Test2 end
Working! Iteration: 4
Working! Iteration: 5
Test0 end
Test3

但我得到:
Test2
Test0
Working! Iteration: 0
Test1
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Test3

唯一有帮助的是取消注释 supervisorScope在上面的代码中。

我做错了什么?我如何在 ViewModel 中设置全局预期行为,例如,为了避免包装每个 launchsupervisorScope ?

提前致谢。

最佳答案

this answer 中所述,您无法更改已启动协程的作业类型。您唯一可以控制的是它的父作业。因为你首先启动一个顶级协程,然后作为它的子进程启动那些你不想影响其他人的失败,最好的选择是你已经发现的,打开一个内部 supervisorScope .

您无法指定关于给定协程在其子协程失败时的行为方式的全局策略。

关于multithreading - Kotlin Supervisor Job 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60260589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com