c++taskc++-cxppl

Do I ever need create_async within a single-language UWP app?


I want to better understand PPL tasks in managed C++ (as in, C++/CX). One point I'm unclear on is using create_task vs create_async. MS documentation says:

Use create_async only when you have to create functionality that can be accessed from another language or another Windows Runtime component. Use the task class directly when you know that the operation is both produced and consumed by C++ code in the same component."

So if I'm authoring async functions only within a managed C++ UWP app, then is using create_async pointless and I'm better off sticking solely with create_task?


Solution

  • Note that C++/CX is not Managed C++. They share some common syntax extensions (like ref-counted "hat" pointers) but C++/CX is 100% native code and does not run on the managed CLR runtime.

    That said, the use of create_async is required if you want to expose asynchronous operations via a public WinRT interface - regardless of whether the consumer of the interface is C++, C#, JavaScript, or another language. That is because create_async returns a Windows::Foundation::IAsyncAction / IAsyncOperation<T>, which is the type that is supported by WinRT and can be consumed (eg) by the C# await keyword.

    If you are only calling your functions from other C++ code directly (ie, not via a public WinRT interface) then you are not required to use create_async.

    Also note that create_async and create_task do different things -- the former runs a functor as an asynchronous operation and returns an IAsyncFoo for use by other WinRT components, whereas the latter accepts an IAsyncXyz value from another WinRT component and wraps a task object around it.