正确示范
/**
* 不能被取消的任务
*/
@Test
fun `test cancel with NonCancellable`() = runBlocking<Unit> {
val job = launch {
try {
repeat(1000) { i ->
println("job:I'm sleeping ${i}...")
delay(500L)
}
} finally {
withContext(NonCancellable){
println("job : I'm running finally")
delay(1000L)
println("巴拉巴拉变")
}
}
}
delay(1300)
println("main:I'm tired of waiting")
job.cancelAndJoin()
println("main:Now i can quit.")
}
如果不加
withContext(NonCancellable){}
是无法保证里面的延时任务能一定执行完成的。。甚至就不会打印出来巴拉巴拉变