- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我对协程取消的理解:
If a parent coroutine is canceled, the children will stop too. If a child coroutine throws Exception, the sibling and parent coroutine will notice it and stop.
Except for SupervisorJob, it will continue active even though one of the child coroutines is stopped.
fun main() {
val parentScope = CoroutineScope(SupervisorJob())
parentScope.launch {
val childJob = launch {
try {
println("#1")
Thread.sleep(1_000)
println("#2")
} catch (e: Exception) {
println("#3")
}
}
println("#4")
childJob.cancel()
}
Thread.sleep(2_000)
}
#1 is called first because there's no blocking code between child and parent job.
#4 is called because `Thread.sleep` is blocking.
#3 is called because the childJob is cancelled, even though the coroutine is not finished.
#4 is called first because the parent coroutine start first.
#1 is called because even though the childJob is cancelled, there's time for #1 to be executed.
#4
#1
#2
yield
或检查协程状态(
active
,
canceled
,
isCompleted
)。然后,我进行以下调整:
fun main() {
val parentScope = CoroutineScope(SupervisorJob())
parentScope.launch {
val childJob = launch {
try {
println("#1")
Thread.sleep(1_000)
if (isActive) {
println("#2")
}
} catch (e: Exception) {
println("#3")
}
}
println("#4")
childJob.cancel()
}
Thread.sleep(2_000)
}
#4
#1
childJob
后仍如何执行#2? childJob
也从不执行#3? yield
或检查协程状态?因为我认为该代码将更难阅读。 GlobalScope.runBlocking
用于代码段,因为在实际项目中,我们无论如何都不会使用
GlobalScope
。我想使用父子作用域和某些生命周期来创建一个与实际项目尽可能接近的示例。
最佳答案
In code snippet 1, how is #2 still executed after childJob is canceled?
Thread.sleep(1_000)
替换为暂停的
delay,它将被取消。
In code snippet 1, why #3 is never executed even though childJob is called?
In code snippet 2, do we really need to use yield or checking coroutine state every time we want to execute a coroutine code? Because in my opinion, the code will be harder to read.
Is there something wrong my code snippet or my understanding of coroutine?
关于kotlin - 如何在协程的计算代码中正确处理取消?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335077/
在我的设置中,我试图有一个界面 Table继承自 Map (因为它主要用作 map 的包装器)。两个类继承自 Table - 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
Rust Nomicon 有 an entire section on variance除了关于 Box 的这一小节,我或多或少地理解了这一点和 Vec在 T 上(共同)变体. Box and Vec
我是一名优秀的程序员,十分优秀!