Home > database >  Async void in C WinRT
Async void in C WinRT

Time:12-14

I want to call non-blocking code in the void Page::OnNavigatingFrom(NavigatingCancelEventArgs const&) method in C /WinRT.

In C#, I could simply use async void as shown in this answer, but as far as I understand, asynchronous methods need to return IAsyncAction (or one of the other interfaces) in order for me to be able to use co_await etc.

Does anybody know a way to call asynchronous methods in the aforementioned OnNavigatingFrom method or do I have to resort to calling them synchronously (using .get() I believe)?

CodePudding user response:

The concept, where

you have a task that can be done concurrently with other work, and you don't need to wait for that task to complete (no other work depends on it), nor do you need it to return a value

is frequently referred to as "fire and forget". C /WinRT provides the fire_and_forget struct that can be used as a return type in those situations. To use it you need to change the declaration from

void Page::OnNavigatingFrom(NavigatingCancelEventArgs const&)

to

winrt::fire_and_forget Page::OnNavigatingFrom(NavigatingCancelEventArgs)

This allows you (or the framework) to call OnNavigatingFrom without co_await'ing it. The implementation is free to co_await or co_return at any point.

As with any co-routine, make sure to not accept a (const) reference. It will get invalidated at the first suspension point, and chaos ensues in due time. Pass-by-value disarms this C foot gun reliably.

  • Related