作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在程序的几个点上,我使用 launch
来启动执行一些后台任务的协程。然后,在某个时刻,我从 main
函数返回。我的程序的简化版本可能如下所示:
fun main(args : Array<String>)
{
launch {
delay(10000) // some long running operation
println("finished")
}
}
现在,协程按预期启动并开始运行操作 - 然后程序退出。如果我没有从 main
返回或用 thread
替换 launch
,一切都会按预期进行。 那么我该怎么办,因为我没有跟踪程序中启动的所有协程(因此我无法使用 .join()
或 .await( )
),确保所有协程在我的程序退出之前完成?
最佳答案
So how can I, given that I don't keep track of all coroutines started in my program (hence I cannot use .join() or .await()), make sure that all coroutines finish before my program exits?
您需要在某个时刻跟踪并等待结果,以确定这些协程已完成。那是因为“协程就像守护线程”:
Active coroutines do not keep the process alive. They are like daemon threads.
常规 Java Thread
的情况并非如此,它们是 non-daemon默认情况下。
关于kotlin - 当多个协程正在运行时不要退出 Kotlin 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48124944/
我是一名优秀的程序员,十分优秀!