Callbacks and PPL…What’s the Problem?
What is great about the PPL tasks is being able to chain tasks using the .then(…). This makes asynchronous order of execution much easier to understand and write. A problem I came across the other night was how do I combine regular C++ callbacks, whether they be COM callback interfaces, or just a C++ function pointer callbacks? This was difficult with my shallow knowledge of the PPL because the lambda you pass to the task<> constructor is scheduled for execution immediately. This doesn’t play well when you don’t want your task to execute immediately and fire off the “.then(…)” chain. You want that to happen when you get a callback from somewhere else!
What’s a Solution?
The one solution I’ve found is the task_completion_event. The task<> class has a constructor overload that takes this type. Simply said, a task initialized with a task_completion_event does not execute anything initially, but waits for the task_completion_event::set(…) to be called. Once this happens, your task will continue on with it’s .then(…) chain.
Below is a very generic example of the task_completion_event. In a real application, you may have to add a little bit more management internally to make sure your callback executes the correct completion event that corresponds to another native callback.