Calling async code in a sync function

Hello,

I have been trying to call async code in sync code.

From my research I see several problems:

  • async code should only be called in async functions where the uppermost function is marked by something like #[tokio::main] (or a runtime has been instantiated)
  • To block on async code in a sync function it's a big problem. With tokio, as an example, creating / retrieving a Runtime seems more complicated than easy
  • async code does not seem the "answer" to everything (it can cause more problem than it solves (to be confirmed))

To give a bit more context I have async code that needs to be called from a sync function that comes from a trait from an external library.

Thank you very much in advance for any help

This is a guideline for “normal, boring” async programming. Sometimes you have reason to do something else.

The important thing not to do is: if async code calls non-async code, then that non-async code must not do a block_on().[1] If you're going to block on a future than you must do it from a thread that isn't already using async somewhere up the stack.

Keep that in mind and using block_on() won't be any trouble.

If you are already using tokio, then probably what you need is Handle. You can obtain a Handle from the runtime or from inside any task. Handles are clonable, so you can pass them around in ways it would be awkward to do with the Runtime itself.

If you are not already using an async runtime and you are just looking for the most lightweight way to block on a future, you want pollster. It gives you a block_on() function and nothing else.


  1. Even this is an oversimplification; there are cases where it can be okay. ↩︎

5 Likes

Thank you for your great explanation and help.

It completely answers my question.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.