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

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

我真正需要的只是协程调度程序,因此我可以编写类似
launch(threadPool) { ... }

要么
withContext(threadPool) { ... }

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

最佳答案

目前,这还不是开箱即用的解决方案,但是您可以编写自己的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

10-03 00:26