23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

});<br />

}<br />

return task.AsAsyncOperation();<br />

The IAsyncOperation interface returned by this method, like all the async interfaces in<br />

Windows.Foundation, gets projected into JavaScript as a promise, so we can use the usual code to call<br />

the method and receive its results (asyncVars is just an object to hold the variables):<br />

asyncVars.startCS = new Date();<br />

var promiseCS = PixelCruncherCS.Tests.countFromZeroAsync(max, increment);<br />

promiseCS.done(function (sum) {<br />

asyncVars.timeCS = new Date() - asyncVars.startCS;<br />

asyncVars.sumCS = sum;<br />

});<br />

With code like this, which is in the Image Manipulation example with this chapter, you can start the<br />

async counting operations (using the Counting Perf (Async) button) and then immediately go open an<br />

image and do grayscale conversions at the same time.<br />

Async Methods in C++ To implement an async method in C++, we need to produce the same end<br />

result as in C#: a method that returns one of the IAsync* interfaces and runs its internal code on another<br />

thread.<br />

The first part is straightforward—we just need to declare the method with the C++ types (shown<br />

here in the C++ code; the class declaration in Grayscale.h is similar):<br />

using namespace Windows::Foundation;<br />

IAsyncOperation^ Tests::CountFromZeroAsync(double max, double increment)<br />

The C++ analogue of the AsyncInfo class is a task found in what’s called the Parallel Patterns Library<br />

for C++, also known as PPL or the Concurrency Runtime, whose namespace is concurrency (use a<br />

#include and using namespace concurrency; in your C++ code you’re good to go). The<br />

function that creates a task is called create_async. All we need to do is wrap our code in that function as<br />

follows:<br />

IAsyncOperation^ Tests::CountFromZeroAsync(double max, double increment)<br />

{<br />

return create_async([max, increment]()<br />

{<br />

double sum = 0;<br />

for (double x = 0; x < max; x += increment)<br />

{<br />

sum += x;<br />

}<br />

}<br />

return sum;<br />

});<br />

740

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!