Coroutines必须取消合作社
查看官方文档,似乎只有在取消取消时才能取消Coroutine,这意味着它在执行代码之前检查了它是否有效。 link> link
如果情况是这样,范围是如何的。取消()取消所有Coroutines取消/停止在该范围内运行?
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) { // computation loop, just wastes CPU
// print a message twice a second
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
Looking at the official docs, it seems like a coroutine can only be cancelled if it cooperates with cancellation meaning it checks if it's active before executing its code. LINK
If that's the case, how does scope.cancel() cancels all coroutines cancel/stop running inside that scope?
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) { // computation loop, just wastes CPU
// print a message twice a second
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它实际上并没有取消工作。在
job.cancelandjoin()
中,代码等到white(i&lt; 5)
已完成,然后才存在。如果阅读链接的文章到末尾,您将找到合作作业的示例,该示例使用
while(isActive)
。ISACTIVE
返回false
在取消作业时。发生这种情况时,while-loop将正常退出。It doesn't actually cancel the job. In the
job.cancelAndJoin()
the code waits untilwhile (i < 5)
is done and then the job exists.If read the linked article to the end, you'll find the example of a cooperative job, which uses
while (isActive)
.isActive
returnsfalse
when the job gets cancelled. When this happens, the while-loop will just quit normally.