我的代码基本上如下:
var job: Job? = null
fun startJob() = runBlocking(dispatcher) {
job = CoroutineScope(dispatcher).launch { myJob() }
}
suspend fun myJob() {
// work block 1
...
yield()
// work block 2
...
yield()
// work block 3
...
yield()
...
}
fun cancelJob() = runBlocking(dispatcher) {
job?.cancelAndJoin()
}
fun main() {
startJob()
cancelJob()
}
当我使用 dispatcher = Dispatchers.IO 或 Dispatchers.Default 运行上述程序时,它工作正常。但是,设置 dispatcher = TestCoroutineDispatchers 只是挂在 cancelAndJoin() 上。
我怀疑这与 TestCoroutineDispatcher 在处理 yield() 时的行为有关。据此, yield() 只有在 runCurrent() 被调用时才会恢复。但是鉴于我的代码结构,我不确定在哪里调用 runCurrent(),或者它是否是正确的方法。