gpt4 book ai didi

kotlin - 关闭基本的Executor执行程序CoroutineDispatcher

转载 作者:行者123 更新时间:2023-12-02 12:42:47 24 4
gpt4 key购买 nike

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

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

关于kotlin - 关闭基本的Executor执行程序CoroutineDispatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49217668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com