为什么我的程序会退出,即使我生成了一个应该永远循环的任务?
Why does my program exit even though I spawn a task that should loop forever?
当我在 main
中调用 do_update().await
时,它打印出“Foo”,但循环似乎停止了,而不是阻止程序返回。这是什么原因?
async fn do_update() {
task::spawn(async {
let duration = Duration::from_millis(10);
let mut stream = tokio::time::interval(duration);
stream.tick().await;
loop {
println!("Foo");
stream.tick().await;
}
});
}
问题是您需要将任务存储在一个变量中并对其调用.await
,
async fn do_update() {
// here we store it.
let task = task::spawn(async {
let duration = Duration::from_millis(10);
let mut stream = tokio::time::interval(duration);
stream.tick().await;
loop {
println!("Foo");
stream.tick().await;
}
});
// and here we await it.
task.await;
}
否则您创建了任务,但实际上并未指定该任务需要在程序终止之前解决。
当我在 main
中调用 do_update().await
时,它打印出“Foo”,但循环似乎停止了,而不是阻止程序返回。这是什么原因?
async fn do_update() {
task::spawn(async {
let duration = Duration::from_millis(10);
let mut stream = tokio::time::interval(duration);
stream.tick().await;
loop {
println!("Foo");
stream.tick().await;
}
});
}
问题是您需要将任务存储在一个变量中并对其调用.await
,
async fn do_update() {
// here we store it.
let task = task::spawn(async {
let duration = Duration::from_millis(10);
let mut stream = tokio::time::interval(duration);
stream.tick().await;
loop {
println!("Foo");
stream.tick().await;
}
});
// and here we await it.
task.await;
}
否则您创建了任务,但实际上并未指定该任务需要在程序终止之前解决。