如何在move||闭包中使用异步函数

  • 本文关键字:异步 函数 闭包 move rust
  • 更新时间 :
  • 英文 :


我使用任务栏在windows的任务栏中添加一些上下文菜单。(https://docs.rs/tray-item/0.7.0/tray_item/struct.TrayItem.html)。

这个包给了我一个处理菜单点击事件的例子,如下所示:

tray.add_menu_item("CLICK ME", move || handle_click()).unwrap();

问题是我要运行的函数handle_click()是一个异步函数:

// this function does something and returns nothing
// must use async since some_function() is async
pub async fn handle_click() {
match some_function().await {
Ok(_) => println!("Click is happening"),
Err(_) => println!("Error.... >.<),
};
}

我想这会很容易,但我想不通。如果我使用

tray.add_menu_item("CLICK ME", async move || handle_click()).unwrap();

这给出了一个错误:

--> srcmain.rs:68:42
|
68  |     tray.add_menu_item("CLICK ME", async move || handle_click())
|                                          ^^^^^^^^^^^^^ ------------------ the found `async` closure body
|                                          |
|                                          expected `()`, found opaque type

修改后:

tray.add_menu_item("CLICK ME",, move || {
println!("hello world 1!");
async {
println!("hello worold 2!");
test_printer_zpl().await;
};
})
.unwrap();

它可以编译,但async {}块内的任何内容都无法运行。为什么?

异步闭包如今在rust中并不稳定。您必须编写返回异步块的闭包。

tray.add_menu_item("CLICK ME", move || {
async { handle_click().await };
})
.unwrap();

编辑。回答你的新问题"文献缺乏";,所以我不能确定,但add_menu_iterm似乎不接受异步函数。所以返回了Future(异步块(,但没有返回.awaited,所以它什么也不做。如果要在同步上下文中使用异步代码,则必须手动启动执行器。例如,您可以在上尝试tokio的block_o

tray.add_menu_item("CLICK ME", move || {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(handle_click());
})
.unwrap();

最新更新