Mixing the Concurrency PPL Tasks with “Regular” C++ Callbacks

If you are doing C++ programming in Windows 8 and don’t know about the PPL tasks and how they make asynchronous programming much easier, then this post is the wrong starting point for you.

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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s