gpt4 book ai didi

kotlin - 在协程中使用 runBlocking 时会发生什么坏事吗?

转载 作者:行者123 更新时间:2023-12-01 01:39:52 27 4
gpt4 key购买 nike

来自 the documentation of runBlocking 是否清楚为什么从协程中使用它没有意义,例如嵌套它。

它甚至明确指出:

This function should not be used from a coroutine.



但是,可以这样做:
fun main(args: Array<String>) {
runBlocking {
runBlocking {
println("hi")
}
}
}

(IntelliJ) IDE 有点提示

OCvdVKx

但代码编译并运行。

在更复杂的环境中意外完成会发生什么?崩溃?或者可能是死锁?

最佳答案

What can happen when done accidentally in a more complex setting? Crashes? Or maybe Deadlocks?



不,没有那样的。事实上, runBlocking专为支持嵌套而编写:

If the specified dispatcher is an event loop of another runBlocking, then this invocation uses the outer event loop.



您提到的问题实际上与嵌套无关 runBlocking调用,但普遍关注从协程调用任何阻塞代码。我们使用协程的特定目的是避免阻塞线程,因此在其中调用阻塞函数通常是错误的。您将收到相同的警告 Thread.sleep() , java.io通话等

关于kotlin - 在协程中使用 runBlocking 时会发生什么坏事吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529959/

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