【发布时间】:2020-11-28 00:57:45
【问题描述】:
我正在尝试使用不可取消的协程,我编写了以下代码:
fun main(): Unit = runBlocking {
// launch first coroutine
coroutineScope {
val job1 = launch {
withContext(NonCancellable) {
val delay = Random.nextLong(from = 500, until = 5000)
println("Coroutine started. Waiting for ${delay}ms")
delay(delay)
println("Coroutine completed")
}
}
delay(300) // let it print the first line
println("Cancelling coroutine")
job1.cancelAndJoin()
}
}
输出:
Coroutine started. Waiting for 1313ms
Cancelling coroutine
Coroutine completed
到目前为止,一切都按预期进行。但是,如果我直接在launch 函数中传递NonCancellable 上下文(或者更确切地说是Job),则行为会发生变化并且协程会被取消:
fun main(): Unit = runBlocking {
// launch first coroutine
coroutineScope {
val job1 = launch(context = NonCancellable) {
val delay = Random.nextLong(from = 500, until = 5000)
println("Coroutine started. Waiting for ${delay}ms")
delay(delay)
println("Coroutine completed")
}
delay(300) // let it print the first line
println("Cancelling coroutine")
job1.cancelAndJoin()
}
}
输出:
Coroutine started. Waiting for 4996ms
Cancelling coroutine
为什么第二个 sn-p 会产生不同的输出?
【问题讨论】: