My suggestion is that you find a different solution.
Two common solutions are:
- Call
tokio::spawnfromDropto clean up in the background. - Use a scope to enforce cleanup instead of a destructor:
use std::panic::AssertUnwindSafe;
struct MyResource();
async fn get_resource() -> MyResource {
todo!()
}
async fn cleanup_resource(res: MyResource) {
todo!()
}
async fn with_resource<T>(f: impl AsyncFnOnce(&mut MyResource) -> T) -> T {
let mut res = get_resource().await;
let ret = futures::FutureExt::catch_unwind(AssertUnwindSafe(f(&mut res))).await;
cleanup_resource(res).await;
match ret {
Ok(t) => t,
Err(panic) => std::panic::resume_unwind(panic),
}
}
and then you call
with_resource(|res| {
do_stuff(res).await;
});