Home > OS >  C /WinRT using co_await in main()
C /WinRT using co_await in main()

Time:12-18

In a Windows Console Application (C /WinRT) project the entry point is just the standard int main() function.

How can I get started with asynchronous code then?

For example, I want to call a method

winrt::Windows::Foundation::IAsyncAction WriteToFileAsync()
{
    // calls FileIO::WriteTextAsync etc
}

from main.


co_await cannot be used, i.e.

int main()
{
    winrt::init_apartment();
    
    co_await ::WriteToFileAsync();
}

yields the error

function "main" cannot be a coroutine


Am I supposed to use

int main()
{
    winrt::init_apartment();
    
    ::WriteToFileAsync().get();
}

instead?

Is there a better way in general?

CodePudding user response:

As mandated by the C Standard, the main() function cannot be a coroutine. A function is a coroutine if it uses the co_await operator or the co_yield and co_return keywords.

Consequently, you will have to wait for any coroutines called from the main() function to run to completion. C /WinRT provides the extension functions get() and wait_for() for IAsyncAction (and family) to do that.

I'm not aware of anything "better", though I also don't understand why calling get() were bad.

  • Related