multithreading - 协程 Scope、Suspend 和 withContext 查询
问题描述
我在下面有 3 个片段
- 只是范围发射
fun main() = CoroutineScope(Dispatchers.IO).launch { runMe() }
fun rumMe() = doSomething()
- 范围发射与暂停
fun main() = CoroutineScope(Dispatchers.IO).launch { runMe() }
suspend fun rumMe() = doSomething()
- 范围启动与暂停和 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
解决方案
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()
}
推荐阅读
- c++ - QDbus 信号不工作(暂停交付)
- flutter - “Null”类型不是“Map”类型的子类型
' 在类型转换中 - python - Python:为什么当我使用 \t 而不是空格字符时,单词会转到下一行?
- r - for 循环内的 ifelse 函数未产生预期结果
- json - HL7v2 到 FHIR 转换默认 CodeSystem 规则不起作用
- pyspark - 更改 Livy 在 EMR 集群中使用的 Python 版本
- ffmpeg - ffmpeg 是否因 h.264 RTP 输出而损坏?
- python - How can i control multiple logins(like admin login and normal login) with flask login_required decorator
- android - 如何处理片段中的对话框点击
- android - 如何使用 MVVM 正确处理 RecyclerView 中的恒定数据流?