关闭ExecutorCoroutineDispatcher的底层Executor

Shut down the underlying Executor of ExecutorCoroutineDispatcher

我反复发现自己写的代码是这样的:

val threadPoolExecutor = Executors.newCachedThreadPool()
val threadPool = threadPool.asCoroutineDispatcher()

我真正需要的只是协程调度程序,这样我就可以编写类似

的东西
launch(threadPool) { ... }

withContext(threadPool) { ... }

我需要 threadPoolExecutor 才能在清理时将其关闭。有没有办法使用协程调度程序实例来关闭它?

目前这不是 out-of-the 框解决方案,但您可以编写自己的 asCoroutineDispatcher 扩展来提供这样的体验:

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