如何取消协程中的阻止代码 [英] How to cancel the blocking code in the coroutines
问题描述
我具有以下代码结构:
@Throws(InterruptedException::class)
fun method() {
// do some blocking operations like Thread.sleep(...)
}
var job = launch {
method()
}
job.cancelAndJoin()
method
由外部库提供,我无法控制其行为.执行可能会花费很多时间,因此在某些情况下,应通过超时将其取消.
The method
is provided by the external library and I can't control its behaviour. It can take a lot of time for execution, so in some cases it should be canceled by timeout.
我可以使用kotlin协程库提供的withTimeout
函数,但是由于协程的设计,它无法取消带有阻塞的代码.有解决方法吗?
I can use the withTimeout
function provided by the kotlin coroutines library, but it can't cancel a code with blockings due to the coroutines design. It there some workaround to do it?
推荐答案
主要思想是将协程外上下文线程池与可以在旧样式中中断的自然线程一起使用,并从协程订阅取消事件执行.当事件被invokeOnCancellation
捕获时,我们可以中断当前线程.
The main idea is to use the out of coroutines context thread pool with narutal threads that can be interrupted in the old style and subscribe on the cancellation event from the coroutines execution. When the event is catched by invokeOnCancellation
, we can interrupt the current thread.
实现:
val externalThreadPool = Executors.newCachedThreadPool()
suspend fun <T> withTimeoutOrInterrupt(timeMillis: Long, block: () -> T) {
withTimeout(timeMillis) {
suspendCancellableCoroutine<Unit> { cont ->
val future = externalThreadPool.submit {
try {
block()
cont.resumeWith(Result.success(Unit))
} catch (e: InterruptedException) {
cont.resumeWithException(CancellationException())
} catch (e: Throwable) {
cont.resumeWithException(e);
}
}
cont.invokeOnCancellation {
future.cancel(true)
}
}
}
}
它具有与通常的withTimeout
类似的行为,但它还支持运行带有阻塞的代码.
It provides the similar behaviour like usual withTimeout
, but it additionally supports running a code with blockings.
注意:仅当您知道内部代码使用阻塞并且可以正确处理抛出的InterruptedException
时,才应调用它.在大多数情况下,首选withTimeout
功能.
Note: It should be called only when you know, that the inner code use blockings and can correctly process a throwed InterruptedException
. In most cases the withTimeout
function is prefered.
这篇关于如何取消协程中的阻止代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!