簡體   English   中英

如何正確處理/關閉 Kotlin 中的自定義協程調度程序?

[英]How to properly handle/shut down custom coroutine dispatcher in Kotlin?

考慮這段代碼:

val coroutineDispatcher = Executors.newFixedThreadPool(8).asCoroutineDispatcher()

fun main() = runBlocking {
    launch(coroutineDispatcher) { println("'launch' finished execution") }
    println("This will be printed, but 'runBlocking' will never exit")
}

main() function 永遠不會退出,程序將永遠掛起。 但是,如果我使用任何標准調度程序,例如DefaultIO等,程序將在runBlockinglaunch返回后結束。 如果我調用coroutineDispatcher.close() ,程序也會按預期退出。

我的問題是:

如果客戶端代碼無權訪問它,關閉此類調度程序的正確方法是什么? 假設我有以下 function 暴露給客戶端代碼:

private val coroutineDispatcher = Executors.newFixedThreadPool(8).asCoroutineDispatcher()

suspend fun doStuff(block: () -> Unit) {
    withContext(coroutineDispatcher) {
        block()
    }
}

如何確保客戶端代碼完成后程序成功退出? 特別是當doStuff()應該被多次調用時。

您可以向客戶端公開一個dispose/clear function,這只是取消/關閉您的協程 scope

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM