【发布时间】:2021-05-17 08:38:06
【问题描述】:
我正在尝试创建一个功能,该功能会触发可能无法取消的缓慢操作。我希望此操作在超时的协程中运行。由于操作不能如前所述取消,我需要函数在超时后返回,但操作留在后台。
我一直在尝试运行的代码异步运行 10 秒的冗长操作,其超时时间为 5 秒,因此该函数应在超时后返回并让 main 继续其工作,打印“foo execution finished ”,最后 5 秒后,慢速作业将打印“作业结束(经过 10 秒)”。
代码如下:
fun main() {
println("program execution begins")
foo()
println("foo execution finished")
while(true);
}
fun foo() = runBlocking {
val job = async {
val endTimeMillis = System.currentTimeMillis() + (10 * 1000)
while (System.currentTimeMillis() <= endTimeMillis); //blocks for 10 seconds
println("job ends (10 seconds passed)")
}
try {
withTimeout(5000) {
println("start awaiting with 5 secs timeout")
job.await()
}
} catch (ex: TimeoutCancellationException) {
println("out of time")
}
}
然后产生以下结果:
program execution begins
start awaiting with 5 secs timeout
job ends (10 seconds passed)
out of time
foo execution finished
但这并不是我在前面提到的这种情况下需要的行为。我需要使输出看起来像:
program execution begins
start awaiting with 5 secs timeout
out of time
foo execution finished
job ends (10 seconds passed)
除此之外,我不能在异步中使用任何类型的“kotlin-coroutines”函数来归档这种行为(好吧,配合取消),因为那里调用的代码将与用户代码无关协程,可能是用 Java 编写的。因此用于阻塞异步块的 while 循环而不是示例中的 delay()。
提前感谢您的帮助!
【问题讨论】:
-
@Alex.T 它不会直接“返回某些东西”,而是通过我制作的单独机制将数据发送到我程序的另一部分。但是我仍然需要等待该数据发送才能继续,或者如果花费的时间太长则超时并继续前进,这样我的整个程序就不会冻结。
-
对不起,误删了评论。对于任何想知道的人,我在问
async块是否有预期的实际返回值。
标签: kotlin asynchronous