简体   繁体   中英

Passing callback into tokio task

I have a function that takes a callback as a parameter:

fn my_function (on_complete: Box<dyn FnOnce(bool)) {
    // Do some work
    on_complete(false);
}

The work I do before calling is pretty heavy though, so I'm trying to spawn it off into a task:

fn my_function (on_complete: Box<dyn FnOnce(bool)) {
    tokio::spawn(async move{
        // Do some work
        on_complete(false);
    });
}

This is giving me all sorts of ownership issues, namely that my Box can't be safely shared across threads. I've tried a number of things to get around this, including obvious ones like borrowing and more traditional threading solutions like passing it as an Arc>, but can't seem to get anywhere.

Any suggestions on how to do this correctly?

You need to mark your boxed callback as thread-safe with Send :

fn my_function (on_complete: Box<dyn FnOnce(bool) + Send>) {
//                                               ^^^^^^^
    tokio::spawn(async move{
        // Do some work
        on_complete(false);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM