gpt4 book ai didi

android - 即使协程上下文不是 Dispatchers.Main,runBlocking(Dispatchers.IO) 是否也会阻塞主线程?

转载 作者:行者123 更新时间:2023-12-04 23:52:48 27 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

这就是文档所说的:

When CoroutineDispatcher is explicitly specified in the context, thenthe new coroutine runs in the context of the specified dispatcherwhile the current thread is blocked. If the specified dispatcher is anevent loop of another runBlocking, then this invocation uses the outerevent loop.

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

关于android - 即使协程上下文不是 Dispatchers.Main,runBlocking(Dispatchers.IO) 是否也会阻塞主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64768650/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com