【问题标题】:Shut down the underlying Executor of ExecutorCoroutineDispatcher关闭 ExecutorCoroutineDispatcher 的底层 Executor
【发布时间】:2018-08-19 10:28:35
【问题描述】:

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

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

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

launch(threadPool) { ... }

withContext(threadPool) { ... }

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

【问题讨论】:

    标签: kotlin kotlinx.coroutines


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-28
      • 2013-10-31
      • 2018-01-31
      • 2017-09-21
      • 2017-09-29
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多