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

标签 kotlin coroutine kotlin-coroutines

来自 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/

相关文章:

c++ - 在协程调用 `Segmentation fault` 之后,是什么导致此代码 `promise_type::return_value()` ?

multithreading - 在协程之间共享变量

python - 如果 Python 生成器不再使用但尚未达到 StopIteration,它会被垃圾收集吗?

Spring Transactional - 确保测试和产品中的可预测行为

spring - @ControllerAdvice处理异常,但不自定义响应

android - 如何在 fragment 中初始化 "lateinit binding"?

kotlin - 暂停功能中写入或不暂停的协程/恢复的区别是什么

android - StackOverflowError 在 Kotlin 中使用 Singleton

android - 从 viewModelScope 中的 Flow 收集数据是否会阻止 Android Studio 中的 UI?

kotlin - 如何在 kotlin 中创建这个协程?