有人可以从实际的角度,即在哪种情况下将一种场景用于另一种场景,来解释Kotlin Coroutine的ExecutorCoroutineDispatcher
和CoroutineDispatcher
之间的区别吗?
到目前为止,我一直在使用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()'
}