在我的一个actix-web处理程序中,我想调用一个在后台运行的函数并立即向用户返回响应:
async fn heavy_computation() -> {
// do some long running computation
}
async fn index(req: HttpRequest) -> impl Responder {
// start computation
heavy_computation();
// render and return template
let out context = Context::new();
context.insert("foo", "bar");
render_template("my_template.html", &context)
// computation finishes
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(web::resource("/").route(web::get().to(index)))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
如果我对将来进行await
编码,则直到计算完成后才进行响应;如果不对它进行await
编码,则根本不会执行该功能。
最佳答案
假设您使用tokio
作为异步运行时,则可以使用tokio::task::spawn
生成两个任务,然后将它们与tokio::join
结合在一起:
use tokio::task;
use tokio::time;
use std::time::Duration;
async fn heavy_computation() {
time::delay_for(Duration::from_millis(2000)).await;
println!("heavy computation finished");
}
async fn light_computation() {
time::delay_for(Duration::from_millis(500)).await;
println!("light computation finished");
}
#[tokio::main]
async fn main() {
let heavy = task::spawn(heavy_computation());
println!("computation started");
let light = task::spawn(async move {
for _ in 0..3 {
light_computation().await;
}
});
let (a, b) = tokio::join!(heavy, light);
// use the results so the compiler doesn't complain
a.unwrap();
b.unwrap();
}
Link to playground
关于rust - 返回响应后,在后台运行长时间运行的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62982737/