Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...