来自 the documentation of runBlocking
是否清楚为什么从协程中使用它没有意义,例如嵌套它。
它甚至明确指出:
This function should not be used from a coroutine.
但是,可以这样做:
fun main(args: Array<String>) {
runBlocking {
runBlocking {
println("hi")
}
}
}
(IntelliJ) IDE 有点提示
但代码编译并运行。
在更复杂的环境中意外完成会发生什么?崩溃?或者可能是死锁?
最佳答案
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/