从协程中使用 runBlocking 时会发生不好的事情吗?
Can something bad happen when using runBlocking from a coroutine?
从 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
调用等,您会收到相同的警告。
从 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
调用等,您会收到相同的警告。