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.

Interface (in Windows.Foundation)<br />

IAsyncAction<br />

IAsyncActionWithProgress<br />

IAsyncOperation<br />

IAsyncOperationWithProgress<br />

Use Case<br />

Use for an async method that produces no results (no arguments<br />

are sent to the completed handler) and reports no progress.<br />

Use for an async method that produces no results but does report<br />

progress, where is the data type of the argument<br />

sent to the progress handler.<br />

Use for an async method that produces results of type <br />

but reports no progress.<br />

Use for an async method that produces results of type <br />

and reports progress with type to a progress<br />

handler.<br />

Having chosen the type of async method we’re creating, we now have to run the method’s code on<br />

another thread. It is possible here to utilize threads directly, using the thread pool exposed in the<br />

Windows.System.Threading API, but there are higher level constructs in both C#/VB and C++ that<br />

make the job much easier.<br />

Async Methods in C#/Visual Basic In C# and Visual Basic we have the<br />

System.Threading.-Tasks.Task class for this purpose. A Task is created through one of the static<br />

Task.Run methods. To this we give an anonymous function (called a delegate in .NET, defined with a<br />

lambda operator =>) that contains the code to execute. To then convert that Task into an appropriate<br />

WinRT async interface, we call the task’s AsAsyncAction or AsAsyncOperation extension method. Here’s<br />

what this looks like in a generic way:<br />

public IAsyncOperation SomeMethodAsync(int id)<br />

{<br />

var task = Task.Run( () => // () => in C# is like function () in JS<br />

{<br />

return "Here is a string.";<br />

});<br />

}<br />

return task.AsAsyncOperation();<br />

If the code inside the task itself performs any asynchronous operations (for which we use the C#<br />

await keyword as described in the blog posts linked earlier), the delegate must be marked with async:<br />

public IAsyncOperation SomeMethodAsync(int id)<br />

{<br />

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

{<br />

var idString = await GetMyStringAsync(id); // await makes an async call looks sync<br />

return idString;<br />

});<br />

}<br />

return task.AsAsyncOperation();<br />

738

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

Saved successfully!

Ooh no, something went wrong!