gpt4 book ai didi

kotlin - 即使使用Kotlin Coroutines启动,也确保主JVM程序能够运行

转载 作者:行者123 更新时间:2023-12-03 08:40:35 24 4
gpt4 key购买 nike

我有一个非常简单的Kotlin程序,例如

  fun main() {
val scope = CoroutineScope(Dispatchers.Default)

val job = scope.launch() { // I only check if this Job isActive later
withTimeout(2000) {
terminate(task)
}
}

}

private suspend fun terminate(task: Task): Nothing = suspendCoroutine {
throw IllegalAccessError("Task ${task.name} should honor timeouts!")
}

Terminate()调用时,我希望我的程序能够启动。我不想恢复。但是,我不能只看
Exception in thread "DefaultDispatcher-worker-2" 
abc.xyz.mainKt$terminate$$inlined$suspendCoroutine$lambda$1: Task Robot should honor timeouts!
// More stacktrace ...


在日志中,因为协程正在“吞噬”此异常。

因此,我的问题是:采用Kotlin Coroutines驱动的设计,当超时发生时,如何保证我的程序能得到保证?

最佳答案

这个怎么样?

fun main() = runBlocking {

withTimeout(2000) {
terminate(task)
}
}

关于kotlin - 即使使用Kotlin Coroutines启动,也确保主JVM程序能够运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61903226/

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