Coroutines必须取消合作社

发布于 2025-01-25 10:31:16 字数 874 浏览 1 评论 0原文

查看官方文档,似乎只有在取消取消时才能取消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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狠疯拽 2025-02-01 10:31:16

它实际上并没有取消工作。在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 until while (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 returns false when the job gets cancelled. When this happens, the while-loop will just quit normally.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文