gpt4 book ai didi

kotlin - 当多个协程正在运行时不要退出 Kotlin 程序

转载 作者:行者123 更新时间:2023-12-02 09:18:50 24 4
gpt4 key购买 nike

在程序的几个点上,我使用 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/

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