【问题标题】:Does runBlocking(Dispatchers.IO) block the main thread even the the coroutine context is not Dispatchers.Main?即使协程上下文不是 Dispatchers.Main,runBlocking(Dispatchers.IO) 是否也会阻塞主线程?
【发布时间】:2020-11-10 12:07:27
【问题描述】:

我正在使用 Kotlin 学习 Android,并且我了解到在不阻塞主线程的情况下启动协程的推荐方法是执行以下操作

MainScope().launch {
  withContext(Dispatchers.IO) {
    // Do IO work here
  }
}

但我也想知道 not 下面的调用是否会阻塞主线程,因为它仍在使用Dispatchers.IO

runBlocking(Dispatchers.IO) {
  // Do IO work here
}

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    如果您从主线程调用runBlocking(Dispatchers.IO),那么当协程在 IO-dispatcher 上完成时,主线程将被阻塞。

    这就是文档所说的:

    当在上下文中显式指定 CoroutineDispatcher 时,则 新协程在指定调度程序的上下文中运行 而当前线程被阻塞。如果指定的调度程序是 另一个 runBlocking 的事件循环,则此调用使用外部 事件循环。

    您可以在此处找到文档:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2014-08-26
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多