继续 Kotlin 协程任务在取消后。

huangapple go评论50阅读模式
英文:

continue Kotlin coroutine job after cancellation

问题

我希望在一个Kotlin协程被取消后做一点工作(在这个协程内部有一个延迟函数)。使用线程,我可以捕获InterruptedException并做一些工作,然后结束线程。但是使用Kotlin协程,在调用取消后,当执行到延迟函数时,它立即取消了作业。

我知道如果我在协程内部使用Thread.sleep,它会起作用。但是有没有更好的解决方案?我希望在取消后继续作业,而不是在作业被取消时运行一些代码。

英文:

I want to do a little word after a kotlin coroutine is cancelled. (I have a delay function inside this coroutine). by using threads, I can catch InterruptedException and do some work, then finish the thread. but with Kotlin coroutines, it cancels the job immediately after calling cancel, when execution reaches the delay function.

I know if I use Thread.sleep inside coroutine, it will do the job. but is there any better solution?
I want to continue job after cancellation, not run some code if job is canceled

答案1

得分: 1

使用 withContext(NonCancellable) { ... }。在此上下文中运行的代码不会对外部协程的取消做出反应。这意味着诸如 delay 这样的函数不会抛出 CancellationException

您可以与 try/finally 结合使用,以在协程取消后运行挂起代码。

在此示例中,对 delay 的调用将延迟协程的终止,并且即使协程已被取消,也不会抛出 CancellationException

try {
    // 进行操作
} finally {
    withContext(NonCancellable) {
        delay(1000)
    }
}

有关此机制的更多详细信息,请参阅Kotlin文档。如果您想要更多细节,我还写了一篇更长的文章,介绍了它的工作原理。

请注意,您无法“取消取消”协程。使用 try/finallyNonCancellable 结合主要用于运行清理任务。协程 Job 仍标记为已取消,并且协程仍应确保最终终止。

英文:

Use withContext(NonCancellable) { ... }. Code run inside this context won't react to cancellation of the outer coroutine. That means that functions like delay won't throw CancellationException.

You can use this in combination with try/finally to run suspending code after coroutine cancellation.

In this example, the call to delay will delay the termination of the coroutine, and won't throw a CancellationException, even if the coroutine has been cancelled.

try {
    // do stuff
} finally {
    withContext(NonCancellable) {
        delay(1000)
    }
}

This mechanism is described in more detail in the Kotlin docs. If you want even more detail, I've also written a longer article about how it works.

Note that you can't "un-cancel" the coroutine. Using try/finally in combination with NonCancellable is primarily intended for running cleanup tasks. The coroutine Job is still marked as cancelled, and the coroutine should still ensure that it eventually terminates.

huangapple
  • 本文由 发表于 2023年5月17日 15:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定