0

I can't seem to manage to implement the async function into the Drop. This is a sample of what I've tried already, it gives me an error of not finding the event loop.

use anyhow::Result;
use bollard::container::RemoveContainerOptions;
use bollard::Docker;

struct MyStruct;

impl MyStruct {
    pub async fn do_something(&self) -> Result<()> {
        let docker = Docker::connect_with_unix_defaults()?;
        docker
            .remove_container(
                "container-name",
                Some(RemoveContainerOptions {
                    force: true,
                    ..Default::default()
                }),
            )
            .await?;
        Ok(())
    }
}

impl Drop for MyStruct {
    fn drop(&mut self) {
        tokio::task::spawn_blocking(move || {
            let my_struct = MyStruct;
            let handle = tokio::runtime::Handle::try_current().unwrap();
            handle.block_on(async {
                my_struct.do_something().await.unwrap();
            });
        });
    }
}
Kristi R
  • 1
  • 1
  • 1
    Can you give a reproducible example? [When I try to reproduce it works just fine](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9b0f456255690ab644d8ee75c17a9f14). – Chayim Friedman Jul 12 '22 at 11:05
  • 1
    Calling block_on in the Drop impl can have unwanted consequences, it will block the tokio worker thread in the snippet linked by @Netwave, preventing other futures to be executed until the block_on inside the Drop is finished. – sebpuetz Jul 12 '22 at 11:40
  • Can you provide the main function that is wrapping the call to `do_something()`? Your error implies that `Handle::try_current` fails to get a runtime handle which means that dropping happens outside the scope of the tokio runtime. – sebpuetz Jul 12 '22 at 15:04
  • Since the Drop trait isn't meant to natively work with asynchronous code, I see that you're working around it by blocking in the destructor. Not sure how reliable that is, but you may want to give a look at the [async_destruction](https://crates.io/crates/async_destruction) crate. I've never used it, but it supposedly does the job. – Brian Reading Jul 12 '22 at 18:58

0 Answers0