【问题标题】:What's the use of runBlocking in kotlin if it blocks the current thread? [duplicate]如果它阻塞当前线程,kotlin 中的 runBlocking 有什么用? [复制]
【发布时间】:2021-12-18 04:53:52
【问题描述】:

我目前正在开发一个在很多地方都使用runBlocking 的代码库。 这是一个例子

fun doSomeComputation() {
    val rows = runBlocking { //suspend function which queries database }
    //rows is used for further computation
}

据我了解runBlocking 阻塞了当前线程。那么通过使用它而不是使用常规函数,我们到底得到了什么好处呢?读到我们使用异步代码的地方,这样线程就不会被阻塞并且 UI 不会变得无响应,但是如何使用 runBlocking 异步代码,因为它阻塞了线程?
我对 javascript async/await 有同样的疑问 既然线程被阻塞了为什么还要使用await

【问题讨论】:

  • 它可能在主函数中很有用。

标签: kotlin asynchronous async-await kotlin-coroutines nonblocking


【解决方案1】:

这正是我们不应该像您一样使用runBlocking() 的原因。 runBlocking() 对于启动我们的应用程序很有用,例如我们可以在 main() 中放置一个 runBlocking() 来引导协程,然后我们不会在其他任何地方使用它。如果阻塞是我们的预期结果,那么桥接可挂起和不可挂起的代码也很有用。但除此之外,我们应该避免使用它。

如果我们需要桥接经典代码和可挂起代码,但又不想阻塞线程,那么我们需要坚持经典的异步技术,如期货或回调。

【讨论】:

  • javascript 中的 await 怎么样?我觉得推荐使用。但它也阻止了线程。那为什么要使用它呢?
  • 我对 JavaScript 不是很熟悉,也从未使用过它的async/await 功能,但我认为它不会阻塞线程。是吗?
  • 我认为确实如此。 const response = await callSomeApi() //code which is using that response executed only after the function is executed
  • 是的,它在这一行等待,但这并不意味着线程被阻塞。这正是 Kotlin 和(我相信)JavaScript 中的 async/await 功能暂停的重点。
  • 知道了。好吧,现在我希望 kotlin 没有介绍 runBlocking。我们的代码库到处都在使用它,为了更清楚,我将它与await 进行了比较。
猜你喜欢
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 2012-03-27
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多