Asynchronous 如何在异步函数调用的闭包内延迟执行?
考虑以下异步函数:Asynchronous 如何在异步函数调用的闭包内延迟执行?,asynchronous,rust,Asynchronous,Rust,考虑以下异步函数: async fn call_me<F>(f : F ) -> Result<(), Error> where F : FnOnce() -> Result<(), Error> { f() } async fn call\u me(f:f)->结果 其中F:FnOnce()->Result{ f() } 是否有任何方法延迟执行内部的f() std::thread::sleep(std::time::Durat
async fn call_me<F>(f : F ) -> Result<(), Error>
where F : FnOnce() -> Result<(), Error> {
f()
}
async fn call\u me(f:f)->结果
其中F:FnOnce()->Result{
f()
}
是否有任何方法延迟执行内部的f()
将当前线程设置为睡眠std::thread::sleep(std::time::Duration::from_millis(…)
只能在异步上下文中使用tokio::time::delay_for(..)
- 异步闭包仍然存在
- 解决方案是直接传递
std::future::future
:
async fn call_me(f : Future) -> Result<(), Error) {
tokio::time::timeout(tokio::time::Duration(1_000), f()).await
}
async fn some_async_function() -> Result<(), Error> {
tokio::time::delay_for(tokio::time::Duration::from_millis(10_000).await;
Ok(()
}
#[tokio:main]
async fn main() {
call_me(some_async_function()).await;
}
async fn call\u me(f:Future)->结果{
东京::时间::延迟(东京::时间::持续时间::从毫秒(10000)。等待;
好(()
}
#[东京:主要]
异步fn main(){
调用我(一些异步函数())。等待;
}
非常类似于异步闭包的是一个闭包,它返回一个未来的
(恰好是一个异步块)
async fn call\u me(f:f)->结果
哪里
F:FnOnce()->Fut,
未来,,
{
等待
}
#[tokio_宏:main]
异步fn main(){
呼叫我(| |异步){
tokio::time::delay_for(std::time::Duration::from_secs(10))。等待;
好(())
})
.等待
.unwrap();
}
是否可以在自己的线程上运行f()
然后您可以在该线程中轻松地使用std::thread::sleep
。不幸的是,该函数最终将由tokio::time::timeout
执行,在一些硬deadlineIff()之后停止
是一个长期运行的同步函数,tokio::time::timeout
也无法停止它。它必须在不同的线程中运行,超时必须终止线程。isf()
非常受CPU限制的任务?好吧,一个解决方案是传递未来本身,而不是结束。如果这有效,我将回答这个问题。这很优雅!