ExecutorCoroutineDispatcher和CoroutineDispatcher之间的区别

有人可以从实际的角度,即在哪种情况下将一种场景用于另一种场景,来解释Kotlin Coroutine的ExecutorCoroutineDispatcherCoroutineDispatcher之间的区别吗?

到目前为止,我一直在使用Dispatchers,但是(据我所知)它不能给我一个后台线程。这就是我使用newSingleThreadExecutor()的原因。

尽管如此,我注意到的是我的主进程在使用ExecutorCoroutineDispatcher(1)时一直没有结束(使用CoroutineDispatcher时,它按预期完成(2))。经过一番调查,看来我应该在close()上运行方法ExecutorCoroutineDispatcher以完成主要过程(3)。使用CoroutineDispatcher时,您不必这样做,甚至不需要方法close()(4)。 CoroutineDispatcher是否自动关闭?为什么我们有ExecutorCoroutineDispatcher的封闭过程,却没有CoroutineDispatcher的封闭过程?

以下是我用于测试的代码:

fun main() = runBlocking<Unit> {
    val dispatcher1 = Executors.newSingleThreadExecutor().asCoroutineDispatcher() // (1) <-- main process runs indefinitely w/o closing dispatcher1 (3)
    val dispatcher2 = Dispatchers.Unconfined // (2)
    println("Start")

    launch(dispatcher1) {
        println("Child")
        delay(1000)
        printInfo(coroutineContext,this)
    }.join()

    println("End")
    dispatcher1.close() // (3) <-- need to close dispatcher1 for the main process to finish,otherwise it runs indefinitely
//    dispatcher2.close() // (4) <-- dispatcher2 doesn't have method 'close()'
}
linwehao 回答:ExecutorCoroutineDispatcher和CoroutineDispatcher之间的区别

  

CoroutineDispatcher是否自动关闭?为什么我们有ExecutorCoroutineDispatcher的封闭过程,却没有CoroutineDispatcher的封闭过程?

区别不在于调度程序类型,而在于如何配置底层Java Executor服务。缺省的共享执行程序使用守护程序线程,这些线程不会阻止JVM关闭。如果愿意,您可以为自己的执行者获得相同的东西:

val myExecutor = Executors.newSingleThreadExecutor { task ->
    Thread(task).also { it.isDaemon = true }
}

val myDispatcher = myExecutor.asCoroutineDispatcher()

suspend fun main() {
    withContext(myDispatcher) {
        println("On my dispatcher")
    }
}
本文链接:https://www.f2er.com/3103401.html

大家都在问