关闭基础执行器ExecutorCoroutineDispatcher [英] Shut down the underlying Executor of ExecutorCoroutineDispatcher
问题描述
我反复发现自己是这样写代码的:
I repeatedly find myself writing code as this:
val threadPoolExecutor = Executors.newCachedThreadPool()
val threadPool = threadPool.asCoroutineDispatcher()
我真正需要的只是协程调度程序,这样我就可以写类似的东西
What I really need is just the coroutine dispatcher so I can write stuff like
launch(threadPool) { ... }
或
withContext(threadPool) { ... }
,我需要threadPoolExecutor
才能够在清理时将其关闭.有没有办法使用协程调度程序实例将其关闭?
and I need the threadPoolExecutor
just to be able to shut it down on cleanup. Is there a way to use the coroutine dispatcher instance to shut it down instead?
推荐答案
目前,这不是开箱即用的解决方案,但是您可以编写自己的asCoroutineDispatcher
扩展来提供这种体验:
At the moment this is no out-of-the box solution, but you can write your own asCoroutineDispatcher
extension to provide such an experience:
abstract class CloseableCoroutineDispatcher : CoroutineDispatcher(), Closeable
fun ExecutorService.asCoroutineDispatcher(): CloseableCoroutineDispatcher =
object : CloseableCoroutineDispatcher() {
val delegate = (this@asCoroutineDispatcher as Executor).asCoroutineDispatcher()
override fun isDispatchNeeded(context: CoroutineContext): Boolean = delegate.isDispatchNeeded(context)
override fun dispatch(context: CoroutineContext, block: Runnable) = delegate.dispatch(context, block)
override fun close() = shutdown()
}
此问题导致了以下更改请求: https://github.com /Kotlin/kotlinx.coroutines/issues/278
This question had lead to the following change request: https://github.com/Kotlin/kotlinx.coroutines/issues/278
这篇关于关闭基础执行器ExecutorCoroutineDispatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!