首页 > 解决方案 > 协程 Scope、Suspend 和 withContext 查询

问题描述

我在下面有 3 个片段

  1. 只是范围发射
    fun main() = CoroutineScope(Dispatchers.IO).launch { runMe() }
    fun rumMe() = doSomething()
  1. 范围发射与暂停
    fun main() = CoroutineScope(Dispatchers.IO).launch { runMe() }
    suspend fun rumMe() = doSomething()
  1. 范围启动与暂停和 withContext
    fun main() = CoroutineScope(Dispatchers.IO).launch { runMe() }
    suspend fun rumMe() = withContext(Dispatchers.Default) { doSomething() }

我看到它们在与主线程不同的线程中启动,并且异步运行而不阻塞主线程。

我想知道他们有什么不同?如果它们都相同,那么 1 是最好的。如果不是,我什么时候应该使用 2 或 3?

我试过读这个,但看不清楚https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761

标签: multithreadingkotlincoroutinekotlin-coroutines

解决方案


1和2是一样的。仅当函数对协程执行某些操作时,您才必须向函数添加suspend修饰符。

第一种和第三种情况的区别:

fun main() = CoroutineScope(Dispatchers.IO).launch { 
    // io thead executor
    runMe()
}
// still io thread executor
fun rumMe() = doSomething()

fun main() = CoroutineScope(Dispatchers.IO).launch { 
    // io thead executor
    runMe()
}
suspend fun rumMe() = withContext(Dispatchers.Default) { 
    // default/cpu thead executor
    doSomething()
}

推荐阅读