简体   繁体   English

Kotlin 协程执行顺序?

[英]Kotlin coroutine execution order?

Can someone enlighten me about what is going on in this code example:有人可以告诉我这个代码示例中发生了什么:

import kotlinx.coroutines.*
import kotlin.time.*

fun subTask(scope: CoroutineScope): Job {
    val job = scope.launch(Dispatchers.IO){
        println("SubTask started.")
        delay(500L) 
        println("SubTask ending.")
    }
    job.invokeOnCompletion(object: CompletionHandler{
        override fun invoke(cause: Throwable?) {
            println("SubTask completed.")
        }
    })
    return job
}

fun main() {
    val duration = measureTime {
        runBlocking {
            val job = withContext(Dispatchers.IO) {
                subTask(this)
            }
            println("Waiting for SubTask") 
            job.join()
        }
    }
    println("Duration: $duration")
}

(Click here for Kotlin playground) (点击此处查看 Kotlin 游乐场)

I was expecting to see我期待看到

SubTask started.
Waiting for SubTask
SubTask ending.
SubTask completed.
Duration: 600ms

But I am getting但我越来越

SubTask started.
SubTask ending.
SubTask completed.
Waiting for SubTask
Duration: 600ms

Why isn't the subTask run in parallel with main()?为什么 subTask 不与 main() 并行运行?

withContext suspends until it is complete. withContext挂起,直到完成。 Since you are passing the scope of the withContext to subTask() and subTask() uses it to launch its job, withContext will suspend until this other launched job completes.由于您将 withContext 的withContextsubTask()并且subTask()使用它来启动其作业, withContext将暂停,直到另一个已启动的作业完成。 If subTask() used a different CoroutineScope , or if you had not wrapped your subTask() call in withContext , you would have had your expected behavior.如果subTask()使用了不同的CoroutineScope ,或者您没有将subTask()调用包装在withContext中,那么您将获得预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM