当我在 Android 中运行下面的代码时,它运行良好。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runBlocking {
launch {
Log.d("Track", "main runBlocking pre : ${Thread.currentThread().name}")
delay(500)
Log.d("Track", "main runBlocking post : ${Thread.currentThread().name}")
}
}
}
它打印Track: main runBlocking pre : main
Track: main runBlocking post : main
但是,如果我将 Main 上下文提供给 runBlocking
,正如我在下面 override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runBlocking(Dispatchers.Main) { // Provide Dispatchers.Main
launch {
Log.d("Track", "main runBlocking pre : ${Thread.currentThread().name}")
delay(500)
Log.d("Track", "main runBlocking post : ${Thread.currentThread().name}")
}
}
}
它挂起而不运行它。注:
Dispatchers.Main
正在使用implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'
为什么挂了?我以为不提供
Dispatchers.Main
到runBlocking
是让它在主线程中运行,这与提供 Dispatchers.Main
相同。 .我是不是理解错了?注:
我使用的库如下
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.4.21"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.2'
最佳答案
runBlocking
的默认调度程序是一个自定义调度程序,它使用调用它的线程来运行协程的延续。这就是当您从 runBlocking
中登录时的原因。协程 block ,它报告它在主线程上。
但是,这与在 Dispatchers.Main.
上运行某些东西不同。 Dispatchers.Main
通过将代码块作为可运行文件发布到主处理程序,从字面上处理协程延续。但是,该处理程序当前正在运行此 onCreate
方法,并且在 onCreate
之前无法处理其队列中的其他消息返回。但是runBlocking
在其子协程返回之前不会返回,所以 onCreate
永远不能回来。
默认 runBlocking
另一方面,调度程序甚至在返回之前直接在当前线程上运行延续。它甚至不知道处理程序。如果你启动一个协程到 Dispatchers.main
来自runBlocking
使用它的默认调度程序,我想你会有同样的挂起。
关于android - 为 runBlocking 提供 Dispatches.Main 挂起 Android App。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65447319/