Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume an awaitable in C++/Cli

async/await gained a lot of popularity in the C# world the past few years. Async functions also tend to spread rapidly within an application: Awaitables need to be awaited, therefore the calling function must be async and is therefore also an awaitable which needs to be awaited,... and so forth.

I'm using a C# library in a C++/Cli project. The library exposes async APIs. The Visual C++ compiler does not support async/await. Hence I have no way to await any of the APIs the library gives me.

I have the following options:

  • Call the async function and "letting it go": Not an option since I often need the return values to proceed.
  • Calling Wait() or accessing the Result property of the Task/Task<T> objects the async function returns: Causes the infamous dead-lock of the UI thread.

Is there any way to make this work? I wouldn't mind executing the async APIs synchronously if I have to.

like image 963
koloman Avatar asked Nov 20 '22 04:11

koloman


1 Answers

To me, it sounds like your problem is more of a symptom of a bigger issue. I personally try to avoid as much as I can putting business logic in a C++-CLI module. Specifically, I try to limit a ref class functionality to 3 main areas:

  • Translating managed method calls to native method calls (that includes transforming parameters if necessary).
  • Translating native return values to managed return values. This can even be translating an asynchronous function receiving a callback to a method returning Task.
  • Translating native events (callbacks) to managed events.

I Might be wrong, but in your situation it sounds like your C++ code is not well decoupled and you end up wiring different parts of it inside a C++-CLI module.

As for your question, I would use Task.ContinueWith family of methods to perform the asynchronous continuation instead of async / await. Yet, If you want the continuation to be invoked on a specific SynchronizationContext (such as UI thread) then special care must be taken to supply the right TaskScheduler.

like image 187
Elad Maimoni Avatar answered Mar 20 '23 19:03

Elad Maimoni