我在 Rust 项目中使用 Tauri,但它不是主要组件,并且在另一个线程上运行(在可用的平台上)。目前,关闭窗口会停止整个应用程序(其中大部分是基于命令行的),我还没有找到更改此行为的方法。
我目前有这个最小的例子:
fn main() {
tauri::Builder::default()
.run(tauri::generate_context!())
.expect("error while running tauri application");
println!("Hello after tauri");
}
应用程序后的打印永远不会触发。如果您尝试将其移动到单独的线程,整个应用程序仍然会关闭:
fn main() {
std::thread::spawn(|| {
tauri::Builder::default()
.any_thread()
.run(tauri::generate_context!())
.expect("error while running tauri application");
});
loop {
println!("Hello during tauri!");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
loop
不起作用,因为tauri有自己的运行时,所以在Tauri的运行时停止之前你的循环代码不会被执行。
因此,根据您想要做什么,您可以做几件事。
1。 未关闭 Tauri 窗口:
防止应用程序退出:
tauri::Builder::default()
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|_app_handle, event| match event {
tauri::RunEvent::ExitRequested { api, .. } => {
api.prevent_exit();
}
_ => {}
});
或者直接关闭窗口而不关闭应用程序(这是在 Mac 上的操作方式):
tauri::Builder::default().on_window_event(|event| match event.event() {
tauri::WindowEvent::CloseRequested { api, .. } => {
event.window().hide().unwrap();
api.prevent_close();
}
_ => {}
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
2。在单独的线程中并行运行循环:
tauri::Builder::default()
.setup(|app| {
let handle = app.handle();
tauri::async_runtime::spawn(async move {
loop {
println!("Hello during tauri!");
// access tauri's app handle here
std::thread::sleep(std::time::Duration::from_secs(1));
}
});
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
3.以异步方式完成逻辑:
如果你能保持简单,在命令中运行循环将会快速而简单。
我建议研究
async
和运行时如何在 Rust 中工作,这里是最受欢迎的 Tokio 的运行时,因为它主要是你最终在生产中得到的。