23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Note that Task.Run does not support progress reporting and the AsAsyncAction and<br />

AsAsyncOperation extension methods don’t support cancellation. In these cases you need to use the<br />

System.Runtime.InteropServices.WindowsRuntime.AsyncInfo class and one of its Run methods as<br />

appropriate to the chosen async behavior. The Task.AsAsyncOperation call at the end is unnecessary<br />

here because AsyncInfo.Run already provides the right interface:<br />

public IAsyncOperation SomeMethodAsync(int id)<br />

{<br />

return AsyncInfo.Run(async (token) =><br />

{<br />

var idString = await GetMyStringAsync(id);<br />

token.ThrowIfCancellationRequested();<br />

return idString;<br />

});<br />

}<br />

In this code, AsyncInfo.Run provides the delegate with an argument of type<br />

System.-Threading.CancellationToken. To support cancellation, you must periodically call the<br />

token’s ThrowIfCancellationRequested method. This will pick up whether the original caller of the async<br />

method has canceled it (for example, calling a promise’s cancel method). Because cancelation is<br />

typically a user-initiated action, there’s no need to call ThrowIfCancellationRequested inside a very<br />

tight loop; calling it every 50 milliseconds or so will keep the app fully responsive.<br />

Alternately, if a method like GetMyStringAsync accepted the CancellationToken, you could just pass<br />

the token to it. One strength of the CancellationToken model is that it’s highly composable: if you<br />

receive a token in your own async call, you can hand it off to any number of other functions you call<br />

that also accept a token. If cancellation happens, the request will automatically be propagated to all<br />

those operations.<br />

Note that WinRT methods can accept a token because of an AsTask overload. Instead of this:<br />

await SomeWinRTMethodAsync();<br />

you can use this:<br />

await SomeWinRTMethodAsync().AsTask(token);<br />

Anyway, given these examples, here’s a noncancellable async version of CountFromZero:<br />

public static IAsyncOperation CountFromZeroAsync(double max, double increment)<br />

{<br />

var task = Task.Run(() =><br />

{<br />

double sum = 0;<br />

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

{<br />

sum += x;<br />

}<br />

return sum;<br />

739

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

Saved successfully!

Ooh no, something went wrong!