<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Windows 8 Tips and Tricks &#187; runtime</title>
	<atom:link href="http://www.windows8tricks.net/tag/runtime/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.windows8tricks.net</link>
	<description>Check out latest news, tips and tricks of Windows 8 including many windows 8 tweaks and optimization tools. We also reviewWindows 8 applications in the App Store such as games, utilities and general applications.</description>
	<lastBuildDate>Wed, 22 May 2013 02:53:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Building your own Windows Runtime components to deliver great Metro style apps</title>
		<link>http://www.windows8tricks.net/2012/08/building-your-own-windows-runtime-components-to-deliver-great-metro-style-apps/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=building-your-own-windows-runtime-components-to-deliver-great-metro-style-apps</link>
		<comments>http://www.windows8tricks.net/2012/08/building-your-own-windows-runtime-components-to-deliver-great-metro-style-apps/#comments</comments>
		<pubDate>Tue, 07 Aug 2012 01:24:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[For Developers]]></category>
		<category><![CDATA[Apps]]></category>
		<category><![CDATA[Building]]></category>
		<category><![CDATA[components]]></category>
		<category><![CDATA[deliver]]></category>
		<category><![CDATA[great]]></category>
		<category><![CDATA[Metro]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[Style]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.windows8tricks.net/2012/08/building-your-own-windows-runtime-components-to-deliver-great-metro-style-apps/</guid>
		<description><![CDATA[For Windows 8, we completely reimagined the platform, allowing you to choose the programming language and technologies you already know to build apps tailored to the device and form factor. With the Windows Runtime, you can even easily use multiple languages within a single app. You can build a great Metro style app with HTML]]></description>
			<content:encoded><![CDATA[<p>For Windows 8, we completely reimagined the platform, allowing you to choose the programming language and technologies you already know to build apps tailored to the device and form factor. With the Windows Runtime, you can even easily use multiple languages within a single app. You can build a great Metro style app with HTML and JavaScript that can interact with the Xbox 360 controller through building your own Windows Runtime component in C++. You can build reusable XAML controls exposed via Windows Runtime components that are instantly consumable by Metro style apps written in both C++ and C#. Essentially, we have let you build apps on the Windows 8 platform using the languages of your choice with no comprises.</p>
<p>In this blog post, we talk about what you need to know to build your own Windows Runtime components.</p>
<h2>The basics</h2>
<p>The Windows Runtime is at the heart of empowering language choice. It exposes so that you can call them from JavaScript, C++, C# and Visual Basic in a way that’s natural and familiar. This same foundation is available to you when building your own APIs too.</p>
<p>A Windows Runtime component that you build and package in your app is typically referred to as a 3<sup>rd</sup> party Windows Runtime component. This differs from 1<sup>st</sup> party components that are already part of the Windows 8 platform. You can write these 3<sup>rd</sup> party Windows Runtime components in C++, C# or Visual Basic. You can call into the APIs they expose from anywhere, including other Windows Runtime components packaged into your app. You can also call into the APIs exposed via Windows Runtime components from any language.</p>
<p>The Windows Runtime components that you write for your app can use Windows Runtime APIs, Win32, COM, .NET APIs or 3<sup>rd</sup> party libraries as long as they are <a href="http://msdn.microsoft.com/library/windows/apps/br211369" target="_blank">supported for Metro style app development</a>. Note that the Windows Runtime components that you build are different from what you traditionally know as C++ DLLs or .NET assemblies that expose APIs. Creating a class library in .Net or a standalone DLL in C++ is not the same as building a Windows Runtime component. Windows Runtime components are declared in .wnmd files that expose Windows Runtime metadata and enable languages such as JavaScript to naturally consume Windows Runtime APIs (for example, pascalCasedNames support for APIs exposed to JavaScript). The Windows Runtime metadata also enables Visual Studio to provide great tooling capabilities such as IntelliSense support.</p>
<h2>Why build your own Windows Runtime components</h2>
<p>Creating Windows Runtime components can help you architect for reusability and language interoperability. Let’s take a look at some app scenarios that showcase how you can use 3<sup>rd</sup> party Windows Runtime components to build better experiences.</p>
<p align="center"><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/5148.xbox_5F00_controller_5F00_0A8E7868.jpg" rel="lightbox[1469]" title="Xbox 360 Controller"><img style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" title="Xbox 360 Controller" border="0" alt="You can integrate your Metro style app with the Xbox 360 Controller for Windows" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/4666.xbox_5F00_controller_5F00_thumb_5F00_62E7FC3D.jpg" width="300" height="234" /></a>    <br /><em>Figure1: Xbox 360 Controller</em></p>
<h3>Using Win32 and COM APIs in your Metro style app</h3>
<p>The platform provided by Internet Explorer 10 enables you to create great Metro style app experiences using HTML, CSS and JavaScript. But what if you have built a game using HTML5 canvas and want to integrate with the Xbox 360 controller for Windows? The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/Ee417001" target="_blank">XInput</a> API, which allows apps to receive input from the controller, exposes Win32 APIs that are not available directly to JavaScript.</p>
<p>This is a great example of where creating a Windows Runtime component can solve this problem and give you the ability to use the XInput APIs in your HTML based Metro style app. The <a href="http://code.msdn.microsoft.com/windowsapps/XInput-and-JavaScript-c72fe535" target="_blank">XInput and JavaScript controller sketch sample</a> showcases exactly that. The sample app contains a game controller Windows Runtime component written in C++ which wraps the functionality exposed by the XInput APIs. The controller sketch HTML-based app uses the game controller C++ Windows Runtime component to enable the interaction with the Xbox 360 controller.</p>
<p>This scenario, impossible to accomplish using HTML and JavaScript alone, is a perfect example of where creating a 3<sup>rd</sup> party Windows Runtime component allows you to complete a complex scenario that you otherwise wouldn’t be able to.</p>
<h3>Computationally Intensive Operations</h3>
<p>Apps created for fields like science, engineering, and maps/geography often have computationally intensive operations. These intensive operations typically require powerful parallel processing and are well suited for C++ to achieve optimal performance. In <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh699893(v=vs.110).aspx" target="_blank">Developing Bing Maps Trip Optimizer, a Metro style app in JavaScript and C++</a> , we see another scenario where creating a Windows Runtime component in C++ allows us to create the best experience in our app.</p>
<p>You wonder why anyone would want to calculate a trip route on local data at all when we could run this computationally intensive task in the cloud on Bing servers. Bing Maps exposes JavaScript APIs to do this, but sometimes an app must run offline. And we also want the user to drag and change the route in real time with touch. If we can run these intense operations locally, we create an even better experience.</p>
<p>By writing our compute-intensive operation in C++ using the parallel task library, we can harness the power of the client to create a great experience for users. Windows Runtime is a great fit for this scenario, allowing us to create our rich client User Interface (UI) in HTML and JavaScript with the Bing Maps AJAX control while running all of our intensive route operations using C++ code that calculates quickly using parallelization.<i> </i></p>
<h3>Libraries</h3>
<p>The community is filled with great libraries that developers put together and shared for everyone to use. In the past, you may have found it challenging to reuse some of these libraries if they didn’t match the programming language your app was implemented in. For example, you built a great .NET app, but couldn’t use a library written in C++ without going through painful interop hoops like PInvoke.</p>
<p>Windows Runtime bridges the language gap in Windows 8, making it possible for a single Windows Runtime component library with a single code base to reach a broader set of developers irrespective of the component’s language or your app’s primary programming language.</p>
<p>You can now create a single Windows Runtime-exposed XAML library of custom controls that both C++ and C# app developers can consume. And you can use various data storage Windows Runtime libraries shared out by developers in your XAML or HTML based Metro style apps. All of these scenarios are possible without the burden of writing any interop code.</p>
<p>We think Windows Runtime will be a boon to the libraries that developers create and share broadly for the community of Metro style app developers. Let’s now take a look at two concrete examples showing the basics of building a 3<sup>rd</sup> party Windows Runtime component in <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh699871(v=vs.110).aspx" target="_blank">C++/CX</a> and C#.</p>
<h2>Scenario 1: Enhancing your app with native audio</h2>
<p>Say we are building a software synthesizer app using XAML backed by app logic written in C#. To add filter support to our music app, we would like to use <a href="http://msdn.microsoft.com/en-us/library/windows/apps/microsoft.directx_sdk.ixaudio2.ixaudio2.aspx" target="_blank">XAudio</a> to have direct control of audio buffers.</p>
<h3>Adding the Windows Runtime component to our solution</h3>
<p>Using Visual Studio, we add a new C++ Windows Runtime component project to our existing solution. This Windows Runtime component wraps the music processing functionality:</p>
<p align="center"><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/7128.new_5F00_xaudiowrapper_5F00_57BE71F3.jpg" rel="lightbox[1469]" title="Adding a new C++ Windows Runtime Component "><img style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" title="Adding a new C++ Windows Runtime Component " border="0" alt="Using Visual Studio to add a new C++ Windows Runtime Component to our music app" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8688.new_5F00_xaudiowrapper_5F00_thumb_5F00_22B1E2C3.jpg" width="600" height="382" /></a>    <br /><em>Figure 2: Adding a new C++ Windows Runtime Component</em></p>
<p>Visual Studio created a C++ project for us to expose APIs for which the implementation will be packaged in a DLL and the Windows Runtime metadata in a winmd file. Both are made available to our C# project.</p>
<h3>Defining the class exposed to our XAML C# project</h3>
<p>We use <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh699871(v=vs.110).aspx" target="_blank">C++/CX</a> to build the APIs that will be exposed to our C# project, but you also can use the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh438466(v=vs.110).aspx" target="_blank">Windows Runtime C++ Template Library</a> (WRL). We start by defining a fairly basic class to encapsulate the XAudio functionality:</p>
<p><strong>XAudioWrapper.h</strong></p>
<blockquote><div id="codeSnippetWrapper">
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);" id="codeSnippet"><span style="color: rgb(204, 102, 51);">#pragma</span> <span style="color: rgb(204, 102, 51);">once</span><br /><br /><span style="color: rgb(204, 102, 51);">#include</span> <span style="color: rgb(0, 96, 128);">&quot;mmreg.h&quot;</span><br /><span style="color: rgb(204, 102, 51);">#include</span> &lt;vector&gt;<br /><span style="color: rgb(204, 102, 51);">#include</span> &lt;memory&gt;<br /><br /><span style="color: rgb(0, 0, 255);">namespace</span> XAudioWrapper<br />{<br />    <span style="color: rgb(0, 0, 255);">public</span> ref <span style="color: rgb(0, 0, 255);">class</span> XAudio2SoundPlayer sealed<br />    {<br />    <span style="color: rgb(0, 0, 255);">public</span>:<br />        XAudio2SoundPlayer(uint32 sampleRate);<br />        <span style="color: rgb(0, 0, 255);">virtual</span> ~XAudio2SoundPlayer();<br /><br />        <span style="color: rgb(0, 0, 255);">void</span> Initialize();<br /><br />        <span style="color: rgb(0, 0, 255);">bool</span>   PlaySound(size_t index);<br />        <span style="color: rgb(0, 0, 255);">bool</span>   StopSound(size_t index);<br />        <span style="color: rgb(0, 0, 255);">bool</span>   IsSoundPlaying(size_t index);<br />        size_t GetSoundCount();<br /><br />        <span style="color: rgb(0, 0, 255);">void</span> Suspend();<br />        <span style="color: rgb(0, 0, 255);">void</span> Resume();<br /><br />    <span style="color: rgb(0, 0, 255);">private</span>:<br />        interface IXAudio2*                     m_audioEngine;<br />        interface IXAudio2MasteringVoice*       m_masteringVoice;<br />        std::vector&lt;std::shared_ptr&lt;ImplData&gt;&gt;  m_soundList;<br />    };<br />}<br /></pre>
</p></div>
</blockquote>
<p>You will first notice the usage of the <b>public</b>, <b>ref</b> and <b>sealed</b> keywords in the class declaration. For a class to be instantiated from another language such as JavaScript or C# in a Metro style app, the class must be declared as public ref class sealed.</p>
<p>The public functionality (methods, properties …) of the class are limited to C++ built-in types or Windows Runtime types. Those are the only types allowed for crossing the language boundary in Windows Runtime components. That being said, you can use the regular C++ library (i.e.: Standard Template Library collections) for the private data members of your class as shown in this code snippet. Those private data members don’t have to follow the rules associated with crossing the language boundary. The Visual Studio compiler emits error messages and provides guidance if you use unsupported constructs.</p>
<h3>Implementing the class exposed in our Windows Runtime component</h3>
<p>Now that we have defined the basic interface for our class, let’s take a look at some of the implemented methods:</p>
<p><b>XAudioWrapper.cpp</b></p>
<blockquote>
<div id="codeSnippetWrapper">
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);" id="codeSnippet">XAudio2SoundPlayer::XAudio2SoundPlayer(uint32 sampleRate) :<br />    m_soundList()<br />{<br />    <span style="color: rgb(0, 128, 0);">// Create the XAudio2 engine</span><br />    UINT32 flags = 0;<br /><br />    XAudio2Create(&amp;m_audioEngine, flags);<br /><br />    <span style="color: rgb(0, 128, 0);">// Create the mastering voice</span><br />    m_audioEngine-&gt;CreateMasteringVoice(<br />        &amp;m_masteringVoice,<br />        XAUDIO2_DEFAULT_CHANNELS,<br />        sampleRate<br />        );<br />}<br /><br /><span style="color: rgb(0, 0, 255);">void</span> XAudio2SoundPlayer::Resume()<br />{<br />    m_audioEngine-&gt;StartEngine();<br />}<br /><br /><span style="color: rgb(0, 0, 255);">bool</span> XAudio2SoundPlayer::PlaySound(size_t index)<br />{<br />    <span style="color: rgb(0, 128, 0);">//</span><br />    <span style="color: rgb(0, 128, 0);">// Setup buffer</span><br />    <span style="color: rgb(0, 128, 0);">//</span><br />    XAUDIO2_BUFFER playBuffer = { 0 };<br />    std::shared_ptr&lt;ImplData&gt; soundData = m_soundList[index];<br />    playBuffer.AudioBytes = soundData-&gt;playData-&gt;Length;<br />    playBuffer.pAudioData = soundData-&gt;playData-&gt;Data;<br />    playBuffer.Flags = XAUDIO2_END_OF_STREAM;<br /><br />    HRESULT hr = soundData-&gt;sourceVoice-&gt;Stop();<br />    <span style="color: rgb(0, 0, 255);">if</span> (SUCCEEDED(hr))<br />    {<br />        hr = soundData-&gt;sourceVoice-&gt;FlushSourceBuffers();<br />    }<br /><br />    <span style="color: rgb(0, 128, 0);">//</span><br />    <span style="color: rgb(0, 128, 0);">// Submit the sound buffer and (re)start (ignore any 'stop' failures)</span><br />    <span style="color: rgb(0, 128, 0);">//</span><br />    hr = soundData-&gt;sourceVoice-&gt;SubmitSourceBuffer(&amp;playBuffer);<br />    <span style="color: rgb(0, 0, 255);">if</span> (SUCCEEDED(hr))<br />    {<br />        hr = soundData-&gt;sourceVoice-&gt;Start(0, XAUDIO2_COMMIT_NOW);<br />    }<br /><br />    <span style="color: rgb(0, 0, 255);">return</span> SUCCEEDED(hr);<br />}<br /></pre>
</p></div>
</blockquote>
<p>In this code snippet, we are just using the XAudio2 COM APIs available for <a href="http://msdn.microsoft.com/library/windows/apps/br211369" target="_blank">Metro style app development</a> to wire up our audio engine, play sound and resume the engine. Additionally, we can use C++ constructs and types beyond just the Windows Runtime types to implement the necessary functionality.</p>
<h3>Adding and consuming the Windows Runtime component</h3>
<p>After we define and implement our basic class, we use Visual Studio to add the XAudioWrapper Windows Runtime component to our C++ project from our C# project:</p>
<p><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/2821.add_5F00_xaudiowrapper_5F00_308428BE.jpg" rel="lightbox[1469]" title="Adding the XAudioWrapper Windows Runtime Component to our music app "><img style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" title="Adding the XAudioWrapper Windows Runtime Component to our music app " border="0" alt="Using Visual Studio to add a reference to the XAudioWrapper Windows Runtime Component in our music app" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3482.add_5F00_xaudiowrapper_5F00_thumb_5F00_10691C01.jpg" width="600" height="412" /></a></p>
<p align="center"><em>Figure 3: Adding the XAudioWrapper Windows Runtime Component to our music app</em></p>
<p>As a result, the class that we expose from our C++ project becomes available to our C# project:</p>
<p><b>MainPage.cs</b></p>
<blockquote>
<div id="codeSnippetWrapper">
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);" id="codeSnippet"><span style="color: rgb(0, 0, 255);">using</span> XAudioWrapper;<br /><br /><span style="color: rgb(0, 0, 255);">namespace</span> BasicSoundApp<br />{    <br />    <span style="color: rgb(0, 0, 255);">public</span> sealed partial <span style="color: rgb(0, 0, 255);">class</span> MainPage : Page<br />    {<br />        XAudio2SoundPlayer _audioPlayer = <span style="color: rgb(0, 0, 255);">new</span> XAudio2SoundPlayer(48000);<br />        <span style="color: rgb(0, 0, 255);">public</span> MainPage()<br />        {<br />            <span style="color: rgb(0, 0, 255);">this</span>.InitializeComponent();<br />        }<br /><br />        <span style="color: rgb(0, 0, 255);">protected</span> override <span style="color: rgb(0, 0, 255);">void</span> OnNavigatedTo(NavigationEventArgs e)<br />        {<br />            _audioPlayer.Initialize();<br />        }<br /><br />        <span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">void</span> Button_Click_1(object sender, RoutedEventArgs e)<br />        {<br />            _audioPlayer.PlaySound(0);<br />        }<br />    }<br />}<br /></pre>
</p></div>
</blockquote>
<p>As shown in the code snippet, we can interact with our XAudio wrapper from C# just as if it were a regular .NET component. We reference its namespace, instantiate the component and start invoking the various methods it exposes. All of this without requiring any DllImports to call into the native code!</p>
<h2>Scenario 2: Using built-in APIs to open a zip file from your app</h2>
<p>Say we are also building a file viewer app using HTML and want to add functionality to allow users of this app to pick zip files. We want to use the APIs already built-into Windows and exposed in the .NET platform for <a href="http://msdn.microsoft.com/en-us/library/windows/apps/system.io.compression.ziparchive(v=vs.110).aspx" target="_blank">handling zip files</a>.</p>
<h3>Adding the Windows Runtime component to our solution</h3>
<p>This is the same step as we have described for our music app, but we now pick the C# Windows Runtime component to wrap the zip processing functionality:</p>
<p align="center"><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/4062.new_5F00_ziputil_5F00_704E0F43.jpg" rel="lightbox[1469]" title="Adding a new C# Windows Runtime Component "><img style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" title="Adding a new C# Windows Runtime Component " border="0" alt="Using Visual Studio to add a new C# Windows Runtime Component to our file viewer app" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/4075.new_5F00_ziputil_5F00_thumb_5F00_692ED2CB.jpg" width="600" height="382" /></a></p>
<p><em>Figure 4: Adding a new C# Windows Runtime Component</em>&#160; </p>
<p>Visual Studio has created a C# project for us to expose the APIs for which both the implementation and Windows Runtime metadata are packaged in a .winmd file and made available to our web project.</p>
<h3>Implementing the class exposed in our Windows Runtime component</h3>
<p>We use C# to build the APIs that will be exposed to our web project, but you can also use Visual Basic. We start by defining a simple C# class to encapsulate the zip functionality:</p>
<p><b>ZipWrapper.cs</b></p>
<blockquote>
<div id="codeSnippetWrapper">
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);" id="codeSnippet"><span style="color: rgb(0, 0, 255);">using</span> System;<br /><span style="color: rgb(0, 0, 255);">using</span> System.Collections.Generic;<br /><span style="color: rgb(0, 0, 255);">using</span> System.IO;<br /><span style="color: rgb(0, 0, 255);">using</span> System.IO.Compression;<br /><span style="color: rgb(0, 0, 255);">using</span> System.Runtime.InteropServices.WindowsRuntime;<br /><span style="color: rgb(0, 0, 255);">using</span> System.Threading.Tasks;<br /><span style="color: rgb(0, 0, 255);">using</span> Windows.Foundation;<br /><span style="color: rgb(0, 0, 255);">using</span> Windows.Storage;<br /><br /><span style="color: rgb(0, 0, 255);">public</span> sealed <span style="color: rgb(0, 0, 255);">class</span> ZipWrapper<br />{<br /><span style="color: rgb(0, 0, 255);">public</span> <span style="color: rgb(0, 0, 255);">static</span> IAsyncOperationWithProgress&lt;IList&lt;string&gt;, <span style="color: rgb(0, 0, 255);">double</span>&gt; EnumerateZipFileAsync(StorageFile file)<br />        {<br />            <span style="color: rgb(0, 0, 255);">return</span> AsyncInfo.Run(async delegate(<br />                System.Threading.CancellationToken cancellationToken, IProgress&lt;<span style="color: rgb(0, 0, 255);">double</span>&gt; progress)<br />            {<br />                IList&lt;string&gt; fileList = <span style="color: rgb(0, 0, 255);">new</span> List&lt;string&gt;();<br />                progress.Report(0);<br /><br />                <span style="color: rgb(0, 0, 255);">using</span> (var stream = await file.OpenStreamForReadAsync())<br />                {<br />                    <span style="color: rgb(0, 0, 255);">using</span> (var archive = <span style="color: rgb(0, 0, 255);">new</span> ZipArchive(stream))<br />                    {<br />                        <span style="color: rgb(0, 0, 255);">for</span> (<span style="color: rgb(0, 0, 255);">int</span> i = 0; i &lt; archive.Entries.Count; i++)<br />                        {<br />                            <span style="color: rgb(0, 128, 0);">// add code for processing/analysis on the file </span><br /> <span style="color: rgb(0, 128, 0);">// content here</span><br /><br />                            <span style="color: rgb(0, 128, 0);">// add to our list and report progress</span><br />                            fileList.Add(archive.Entries[i].FullName);<br />                            <span style="color: rgb(0, 0, 255);">double</span> progressUpdate = ((i + 1) / ((<span style="color: rgb(0, 0, 255);">double</span>)archive.Entries.Count)) * 100; <span style="color: rgb(0, 128, 0);">// percentage</span><br />                            progress.Report(progressUpdate);<br />                        }<br />                    }<br />                }<br /><br />                progress.Report(100.0);<br />                <span style="color: rgb(0, 0, 255);">return</span> fileList;<br />            });<br />        }<br />}<br /></pre>
</p></div>
</blockquote>
<p>This class is public and sealed. Similarly to building C++ Windows Runtime components, this is necessary for other languages to instantiate the class. The static method exposed in the class uses a mixture of Windows Runtime types (such as StorageFile) and as .NET types (such as IList) in the method signature. The rule of thumb is to use Windows Runtime types for defining the public fields, parameters and return types that will be exposed to the other languages. That being said, you can use certain .NET fundamental types (i.e.: DateTimeOffset and Uri) and primitives (i.e.: IList) as is.</p>
<p>You will also notice that the method above leverages the <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/03/20/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime.aspx" target="_blank">Windows Runtime infrastructure for async and progress support</a> that you can (and should) use when defining your Windows Runtime components. As far as the implementation for the Windows Runtime component or any private functionality in the class, you are not limited to only using Windows Runtime types and APIs; you are free to use any of the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230232(v=vs.110).aspx" target="_blank">.NET API surface exposed for Metro app development</a> as shown in the code snippet ZipArchive APIs.</p>
<h3>Adding and consuming the Windows Runtime component</h3>
<p>Now that we have implemented our zip tool wrapper, we use Visual Studio to add a reference to our C# project from our JavaScript project:</p>
<p align="center"><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/1832.add_5F00_ziputil_5F00_770118C6.jpg" rel="lightbox[1469]" title="Adding the ZipUtil Windows Runtime component to our file viewer app "><img style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" title="Adding the ZipUtil Windows Runtime component to our file viewer app " border="0" alt="Using Visual Studio to add a reference to the ZipUtil Windows Runtime component in our file viewer app" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8787.add_5F00_ziputil_5F00_thumb_5F00_56E60C09.jpg" width="600" height="412" /></a></p>
<p><em>Figure 5: Adding the ZipUtil Windows Runtime component to our file viewer app</em></p>
<p></p>
<p>As a result, the class that we have exposed from our C# project becomes available to our web project:</p>
<p><b>program.js</b></p>
<blockquote>
<div id="codeSnippetWrapper">
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);" id="codeSnippet"><span style="color: rgb(204, 102, 51);">function</span> pickSinglePhoto() {<br /><br />    <span style="color: rgb(0, 128, 0);">// Create the picker object for picking zip files</span><br />    var openPicker = <span style="color: rgb(0, 0, 255);">new</span> Windows.Storage.Pickers.FileOpenPicker();<br />    openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;<br />    openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;<br />    openPicker.fileTypeFilter.replaceAll([<span style="color: rgb(0, 96, 128);">&quot;.zip&quot;</span>]);<br /><br />    <span style="color: rgb(0, 128, 0);">// Open the picker for the user to pick a file </span><br />    openPicker.pickSingleFileAsync().then(function (file) {<br />        <span style="color: rgb(0, 0, 255);">if</span> (file) {<br />            ZipUtil.ZipWrapper.enumerateZipFileAsync(file).then(<br />        <span style="color: rgb(204, 102, 51);">function</span> (fileList) {<br />            <span style="color: rgb(0, 0, 255);">for</span> (var i = 0; i &lt; fileList.length; i++)<br />                document.getElementById(<span style="color: rgb(0, 96, 128);">'output'</span>).innerHTML += <span style="color: rgb(0, 96, 128);">&quot; &quot;</span> + fileList[i];<br />        },<br />        <span style="color: rgb(204, 102, 51);">function</span> (prog) {<br />            document.getElementById(<span style="color: rgb(0, 96, 128);">'zipProgress'</span>).value = prog;<br />        }<br />    );<br />        } <span style="color: rgb(0, 0, 255);">else</span> {<br />            document.getElementById(<span style="color: rgb(0, 96, 128);">'output'</span>).innerHTML = <span style="color: rgb(0, 96, 128);">&quot;an error occurred&quot;</span>;<br />        }<br />    });<br />};<br /></pre>
</p></div>
</blockquote>
<p>As you can see, we can interact with our zip tool wrapper from JavaScript just as if it were a regular JavaScript object. We can call into the static method exposed in our Windows Runtime component, and we can do so using JavaScript’s async language constructs such as .then(). </p>
<h2>General guidance</h2>
<p>Not every API you write for your Metro style app should be exposed as a 3<sup>rd</sup> party Windows Runtime component. In general, use Windows Runtime types when you are communicating between programming languages and use types and constructs that are built into the language that you are using for functionality that is not publicly exposed via a Windows Runtime component. Additionally, there are various language-specific features and rules around crossing the language boundary that you need to take into consideration when building your Windows Runtime component. This includes delegates and events, asynchronous operations, method overloading, handling specific data types such as collections, exception handling and debugging tips. You can dive into those topics further by visiting the section on <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441572(v=vs.110).aspx" target="_blank">building Windows Runtime components</a> for your development language.</p>
<h2>In closing</h2>
<p>With Windows Runtime components, you can now mix programming languages and API technologies to build the apps you envision. Windows 8 is about no compromises. There are even no compromises during development, allowing you to mix and match the programming languages that best fit your scenario. We hope this allows you to spend more time thinking about innovation and less time being forced to learn a completely new programming language.</p>
<p>Happy app building!</p>
<p>&#8211; Ines Khelifi, Program Manager, Windows</p>
<h2>References</h2>
<p>In this post, we have merely scratched the surface of what’s possible with building Windows Runtime components. Here are additional resources to help you dive into this further for your app development:</p>
<div align="center">
<table class="b8table" border="0" cellspacing="0" cellpadding="3" width="317" align="center">
<tbody>
<tr>
<td valign="top" width="201">
<p><b>Link</b></p>
</td>
<td valign="top" width="114">
<p><b>Types</b></p>
</td>
</tr>
<tr>
<td valign="top" width="201">
<p align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441572(v=vs.110).aspx">Creating Windows Runtime Components</a></b></p>
</td>
<td valign="top" width="114">
<p>Doc</p>
</td>
</tr>
<tr>
<td valign="top" width="201">
<p align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441569(v=vs.110).aspx">Creating Windows Runtime Components in C++</a></b></p>
</td>
<td valign="top" width="114">
<p>Doc</p>
</td>
</tr>
<tr>
<td valign="top" width="201">
<p align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230301(v=vs.110).aspx">Creating Windows Runtime Components in C# and Visual Basic</a></b></p>
</td>
<td valign="top" width="114">
<p>Doc</p>
</td>
</tr>
<tr>
<td valign="top" width="201">
<p align="left"><a href="http://code.msdn.microsoft.com/windowsapps/Basic-Audio-Sample-9a5bb0b7">XAudio2 audio file playback sample</a></p>
</td>
<td valign="top" width="114">
<p>Sample</p>
</td>
</tr>
<tr>
<td valign="top" width="201">
<p align="left"><b><a href="http://code.msdn.microsoft.com/windowsapps/XInput-and-JavaScript-c72fe535">XInput and JavaScript controller sketch sample</a></b></p>
</td>
<td valign="top" width="114">
<p>Sample</p>
</td>
</tr>
<tr>
<td valign="top" width="201">
<p align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh699893(v=vs.110).aspx">Developing Bing Maps Trip Optimizer, a Metro style app in JavaScript and C++</a></b></p>
</td>
<td valign="top" width="114">
<p>Conceptual documentation</p>
</td>
</tr>
</tbody>
</table>
<hr align="left" size="1" width="33%" /></div>
<div style="clear:both;"></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10337272" width="1" height="1"><br />
<a rel="nofollow" href="http://blogs.msdn.com/b/windowsappdev/archive/2012/08/06/building-your-own-windows-runtime-components-to-deliver-great-metro-style-apps.aspx">Windows 8 app developer blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.windows8tricks.net/2012/08/building-your-own-windows-runtime-components-to-deliver-great-metro-style-apps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keeping apps fast and fluid with asynchrony in the Windows Runtime</title>
		<link>http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime-2/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime-2</link>
		<comments>http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime-2/#comments</comments>
		<pubDate>Mon, 14 May 2012 16:27:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[For Developers]]></category>
		<category><![CDATA[Apps]]></category>
		<category><![CDATA[asynchrony]]></category>
		<category><![CDATA[Fast]]></category>
		<category><![CDATA[fluid]]></category>
		<category><![CDATA[Keeping]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime-2/</guid>
		<description><![CDATA[Human beings are asynchronous by nature, which directly affects how we expect apps to respond to us. The Windows Runtime (WinRT) has embraced this asynchrony as a first-class citizen in the building of fast and fluid Metro style apps. If you are building a Metro style app, you will need to write some asynchronous code]]></description>
			<content:encoded><![CDATA[<p>Human beings are asynchronous by nature, which directly affects how we expect apps to respond to us. The Windows Runtime (WinRT) has embraced this asynchrony as a first-class citizen in the building of fast and fluid Metro style apps. If you are building a Metro style app, you will need to write some asynchronous code at some point. In this blog post, we talk about why asynchronous programming is so prevalent in WinRT, and we’ll give you the basics on how to use it in your apps and some background on how it works.</p>
<h3><b>Fast and fluid apps must be responsive</b></h3>
<p>How many times have you been using a Windows app that stops responding, and you are presented with a greyed version of the app and the spinning donut? Without fail, it always seems to come at the worst possible time. Worse yet, you might end up losing a lot of hard work when this happens. </p>
<p>Users expect apps to be responsive to all interactions. When they use their favorite news reading app, they want to add news feeds, read news articles, save news articles, etc. They should be able to do all of these things even when the app is retrieving the latest articles from the Internet. </p>
<p>This becomes especially important when a user is interacting with your app using touch. Users notice when the app doesn’t “stick to your finger.” Even minor performance problems can degrade the user experience and break the fast and fluid feeling.</p>
<p>An app isn’t fast and fluid if it stops responding to user input. So why do apps stop responding? One major cause is that the app is synchronous; it is waiting for something else to finish (like getting data from the Internet) and can’t respond to your input.</p>
<p>Many modern apps connect to social websites, store data in the cloud, work with files on the hard disk, communicate with other gadgets and devices, etc. Some of these sources have unpredictable latencies, which makes creating fast and fluid apps challenging. Unless built correctly, apps spend more time waiting for the outside environment and less time responding to the user’s needs.</p>
<p>Addressing this connected world was a core principle when we started to design APIs for the Windows Runtime (WinRT). We felt it was important to provide an API surface that was powerful and led to fast and fluid apps by default. </p>
<p>To achieve those goals, we made many potentially I/O-bound APIs asynchronous in the Windows Runtime. These are the most likely candidates to visibly degrade performance if written synchronously (e.g. could likely take longer than 50 milliseconds to execute). This asynchronous approach to APIs sets you up to write code that is fast and fluid by default and promotes the importance of app responsiveness in Metro style app development. </p>
<p>For those of you unfamiliar with asynchronous patterns, think of asynchrony in WinRT as providing a callback number to somebody over the phone. You give the person the number to call you back, you hang up, and then you continue doing any other work you need to. When the person is ready to talk to you, they can call you back at the number you provided. This is the essence of how asynchrony works in WinRT.</p>
<p>To understand more about the asynchronous nature of WinRT, we will first look at how you can use these asynchronous APIs in a straightforward way. Then we will take an under the hood look at what async primitives WinRT has introduced (that the new language features build upon), and how they work. </p>
<h3><b>How to use it: new developer enhancements for asynchrony</b></h3>
<p>In the past, writing asynchronous code was difficult. Our teams building tools for Windows 8 Metro style apps made significant advancements in solving this problem in recent releases. In the .NET Framework 4.0, we introduced the <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx" target="_blank">Task Parallel Library</a>. Then the await keyword was introduced into C# and Visual Basic. C++ invested in technologies like the <a href="http://msdn.microsoft.com/en-us/library/dd492418.aspx" target="_blank">Parallel Patterns Library</a> (PPL). And JavaScript has great tools like <a href="http://blogs.msdn.com/b/ie/archive/2011/09/11/asynchronous-programming-in-javascript-with-promises.aspx" target="_blank">Promises</a>. </p>
<p>Each one of these technologies presents you with a straightforward way to write asynchronous code. By introducing a standard async pattern under the hood that all of these technologies use, we allow you to use these technologies when building Metro style apps regardless of which programming language you use. </p>
<p>In the case of your favorite news app, the code that remains responsive while retrieving news articles is quite simple using the <b>Windows.Web.Syndication.SyndicationClient</b> API. The call to RetrieveFeedAsync returns immediately. This is a great thing because the results might take a long time to come back from the Internet. In the meantime, the UI continues to interact with the user. </p>
<p>The code highlighted in yellow runs after the call to RetrieveFeedAsync is completed. You don’t need to think about all the “start again where you left off” plumbing. And the code is written in a straightforward way as if it was synchronous.</p>
<p align="center">
<div align="center">
<h5>JavaScript code to retrieve RSS feed asynchronously:</h5>
<p><span style="color: #0000ff"></span><br />
<blockquote>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">var</span> title;<br /><span style="color: #0000ff">var</span> feedUri = <span style="color: #0000ff">new</span> Windows.Foundation.Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">var</span> client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><br />client.retrieveFeedAsync(feedUri).<b>done</b>(<span style="background-color: #ffff00">function(feed) {<br />    title = feed.title.text;<br />});<br /></span></pre>
</blockquote>
</div>
<div>&nbsp;</div>
<h5 align="center">C# code to retrieve RSS feed asynchronously:</h5>
<div>
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">var feedUri = <span style="color: #0000ff">new</span> Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br />var client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><span style="background-color: #ffff00">var feed</span> = <b>await</b> client.RetrieveFeedAsync(feedUri);<br /><span style="background-color: #ffff00">var title = feed.Title.Text;</span></pre>
</blockquote>
</div>
<h4 align="left"></h4>
<div>
<h5 align="center">VB code to retrieve RSS feed asynchronously:</h5>
<p><span style="color: #0000ff"></span></p>
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">Dim</span> feedUri = <span style="color: #0000ff">New</span> Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">Dim</span> client = <span style="color: #0000ff">New</span> Windows.Web.Syndication.SyndicationClient();<br /><span style="background-color: #ffff00">Dim feed </span> = <b>Await</b> client.RetrieveFeedAsync(feedUri);<br /><span style="background-color: #ffff00">Dim title = feed.Title.Text;<br /></span></pre>
</blockquote>
</div>
<div>&nbsp;</div>
<h4 align="left"></h4>
<div>
<h5 align="center">C++ code to retrieve RSS feed asynchronously:</h5>
<p><span style="color: #0000ff"></span></p>
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">auto</span> feedUri = ref <span style="color: #0000ff">new</span> Windows::Foundation::Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">auto</span> client = ref <span style="color: #0000ff">new</span> Windows::Web::Syndication::SyndicationClient();<br /><br />task&lt;SyndicationFeed^&gt; retrieveTask(client-&gt;RetrieveFeedAsync(feedUri));<br />retrieveTask.<b>then</b>(<span style="background-color: #ffff00">[this] (SyndicationFeed^ feed) {<br />    this-&gt;title = feed-&gt;Title-&gt;Text;<br />});</span><br /></pre>
</blockquote>
</div>
<div>&nbsp;</div>
<h4 align="center"></h4>
<p>There is no mention of threads, context switching, dispatchers, etc. These new developer enhancements for writing asynchronous code will handle that for you. Code following the async API call is automatically called back in the same context that the original call was made. This means you can go ahead and update the UI with the results without worrying about getting back to the UI thread.</p>
<h3>How to use it: error handling</h3>
<p>Of course, API calls can fail (like losing network connectivity while retrieving RSS feeds). To be truly robust, we need to be resilient in the presence of errors. Using the async functionality in the languages makes handling errors more straightforward. The mechanism to do this varies based on the language.</p>
<p>For JavaScript, we recommend that you always end your Promise chains with <b>done</b>. This ensures that any exceptions captured in the promise chain are visible to the developer (i.e. reported in the error handler, or thrown). <b>Done</b> has the same signature as <b>then</b>. So to handle errors, you simply pass an error delegate into <b>done():</b></p>
<p>&nbsp;</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">var</span> title;<br /><span style="color: #0000ff">var</span> feedUri = <span style="color: #0000ff">new</span> Windows.Foundation.Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">var</span> client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><br />client.retrieveFeedAsync(feedUri).done(<span style="color: #0000ff">function</span>(feed) {<br />    title = feed.title.text;<br />}, <span style="color: #0000ff"><b>function</span>(error) {<br />    console.log(<span style="color: #006080">'an error occurred: '</span>);<br />    console.dir(error);<br />}</b>);</pre>
</blockquote>
<p></div>
<p>To handle the exception in C# or Visual Basic, you use a try/catch block just as you do with synchronous code today:</p>
<p>&nbsp;</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">var</span> title;<br /><span style="color: #0000ff">var</span> feedUri = <span style="color: #0000ff">new</span> Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">var</span> client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><br /><span style="color: #0000ff"><b>try</span><br />{</b><br />    <span style="color: #0000ff">var</span> feed = await client.RetrieveFeedAsync(feedUri);<br />    title = feed.Title.Text;<br />}<br /><span style="color: #0000ff">catch</span> (Exception ex)<br />{<br />    <span style="color: #008000">// An exception occurred from the async operation</span><br />}</b></pre>
</blockquote>
<p></div>
<p>The most common method to use in C++ to handle async errors is to use another task-based continuation that throws the exceptions (you can find other methods for error handling in C++ in the topic <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx" target="_blank">Asynchronous Programming in C++</a> on Dev Center):</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">auto</span> feedUri = ref <span style="color: #0000ff">new</span> Windows::Foundation::Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">auto</span> client = ref <span style="color: #0000ff">new</span> Windows::Web::Syndication::SyndicationClient();<br /><br />task&lt;SyndicationFeed^&gt; retrieveTask(client-&gt;RetrieveFeedAsync(feedUri));<br />retrieveTask.then([<span style="color: #0000ff">this</span>] (SyndicationFeed^ feed) {<br />    <span style="color: #0000ff">this</span>-&gt;title = feed-&gt;Title-&gt;Text;<br />}).<b>then([] (task&lt;<span style="color: #0000ff">void</span>&gt; t) {<br />    <span style="color: #0000ff">try</span><br />    {<br />        t.get();<br />    <span style="color: #008000">// .get() didn't throw, so we succeeded</span><br />    }<br />    <span style="color: #0000ff">catch</span> (Exception^ ex)<br />    {<br />        <span style="color: #008000">// An error occurred</span><br />    }<br />})</b>;<br /></pre>
</blockquote>
<pre></pre>
<p></div>
<p>For more details on how to use these asynchronous improvements (including more scenarios like support cancellation and progress) see:<i></i></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464924.aspx" target="_blank">Asynchronous Programming in the Windows Runtime</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx" target="_blank">Asynchronous Programming in JavaScript</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx" target="_blank">Asynchronous Programming in C++</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh770843.aspx">Asynchronous Programming in .NET</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700337.aspx" target="_blank">How to Handle Errors when using Promises in JavaScript</a><i> on the Windows Dev Center</i> </li>
</ul>
<h3><b>How it works: WinRT async primitives</b></h3>
<p>Async is very powerful, but it can appear that there is a lot of magic that happens here on your behalf. To demystify what is happening, let’s take a look at how asynchrony in WinRT works in a little more detail. Our first step is to investigate the primitives the model is built upon. Most of you won’t have to use these primitives at all (if you find a scenario where you have to do this, we would love to hear the feedback).</p>
<p>Starting with our C# code, let’s look at the actual return type of <b>RetrieveFeedAsync</b> (shown here in C# Intellisense): </p>
<p>&nbsp;<a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3005.intellisense_5F00_17BE4799.jpg" rel="lightbox[1281]" title="Intellisense displayed for RetrieveFeedAsync method"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Intellisense displayed for RetrieveFeedAsync method" border="0" alt="Intellisense displayed for RetrieveFeedAsync method" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/2084.intellisense_5F00_thumb_5F00_373D71A1.jpg" width="592" height="99"></a> <br />&nbsp;<em>Figure 1. Intellisense displayed for RetrieveFeedAsync method</em></p>
<p><b>RetrieveFeedAsync</b> returns an <b>IAsyncOperationWithProgress</b> interface. <b>IAsyncOperationWithProgress</b> is one of 5 interfaces that define the core asynchronous programming surface for WinRT: <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.foundation.iasyncinfo.aspx" target="_blank">IAsyncInfo</a>, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.foundation.iasyncaction.aspx" target="_blank">IAsyncAction</a>, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br206581.aspx" target="_blank">IAsyncActionWithProgress</a>, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br206598.aspx" target="_blank">IAsyncOperation</a>, and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br206594.aspx" target="_blank">IAsyncOperationWithProgress</a>. </p>
<p>The core interface that the WinRT async model is built on is <b>IAsyncInfo</b>. This core interface defines properties of an async operation like current status, the ability to cancel the operation, the error of a failed operation, etc. </p>
<p>As we mentioned earlier, async operations can return results. Async operations in WinRT can also report progress as they are running. The other 4 async interfaces above (<b>IAsyncAction</b>, <b>IAsyncActionWithProgress</b>, <b>IAsyncOperation</b>, and <b>IAsyncOperationWithProgress</b>) define different combinations of results and progress. </p>
<p>&nbsp;</p>
<p><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/7870.Tableshowingdifferentcombinationsofresultsandprogress_5F00_6A66160E.jpg" rel="lightbox[1281]" title="Table showing different combinations of results and progress"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Table showing different combinations of results and progress" border="0" alt="Table showing different combinations of results and progress" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8551.Tableshowingdifferentcombinationsofresultsandprogress_5F00_thumb_5F00_6346D996.jpg" width="640" height="211"></a>&nbsp;&nbsp;&nbsp; <br /><em>Figure 2. Different combinations of results and progress</em></p>
<p>Providing core async primitives in the Windows Runtime enables C#, Visual Basic, C++, and JavaScript to project WinRT async operations in a familiar way to you. </p>
<p><b>Note: The move from cold start to hot start</b></p>
<p>In the Windows 8 Developer Preview released at //build, all async operations in WinRT were started cold. They didn’t start running immediately. They had to be explicitly started by the developer or implicitly started using the async features in C#, Visual Basic, JavaScript, or C++. We received feedback from several sources that this wasn’t intuitive and could cause pain and confusion.</p>
<p>In the Windows 8 Consumer Preview release, you will notice that we removed the Start() method from the WinRT async primitives. Now, our async operations are all started hot. So, the async method launched the operation before returning it to the caller. </p>
<p>This is just one of many changes that you’ll find in the Consumer Preview where we’ve fine-tuned the developer platform based on all the great feedback you have given us.</p>
<p><b>How it works: results, cancellation, and errors with async primitives</b></p>
<p>An async operation starts in the Started state and can progress to one of three other states: Canceled, Completed, and Error. The current state of an async operation is reflected in the Status property of the async operation (represented by the <b>AsyncStatus</b> enum type). </p>
<p>The first thing we do with an async operation is wire up a completed handler. From within the completed handler, we can get the results and use them.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">IAsyncOperationWithProgress&lt;SyndicationFeed, RetrievalProgress&gt; op;<br />            op = client.RetrieveFeedAsync(feedUri);<br /><br />            op.Completed = (info, status) =&gt;<br />            {<br />                SyndicationFeed feed = info.GetResults();<br />                UpdateAppWithFeed(feed);<br />            };<br /></pre>
</blockquote>
<p></div>
<p>Sometimes you may want to cancel an operation. You can do this by calling the Cancel method on the async operation.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">IAsyncOperationWithProgress&lt;SyndicationFeed, RetrievalProgress&gt; op;<br />op = client.RetrieveFeedAsync(feedUri);<br /><b>op.Cancel();</b><br /></pre>
<p></p></blockquote>
</div>
<p>The Completed handler is always called for an async operation regardless of whether it was completed, canceled, or resulted in an error. Call <b>GetResults</b> only when the async operation was completed (e.g. not when the operation is canceled or ends in an error). You can determine this by inspecting the status parameter.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">IAsyncOperationWithProgress&lt;SyndicationFeed, RetrievalProgress&gt; op;<br />            op = client.RetrieveFeedAsync(feedUri);<br />            op.Cancel();<br /><br />            op.Completed = (info, status) =&gt;<br />            {<br />                <span style="color: #0000ff"><b>if</span> (status ==</b> AsyncStatus.<b>Completed)</b><br />                {<br />                    SyndicationFeed feed = info.GetResults();<br />                    UpdateAppWithFeed(feed);<br />                }<br />                <span style="color: #0000ff"><b>else</span> <span style="color: #0000ff">if</span> (status ==</b> AsyncStatus.<b>Canceled)</b><br />                {<br />                    <span style="color: #008000">// Operation canceled</span><br />                }<br />            };<br /></pre>
</blockquote>
<pre></pre>
<p></div>
<p>This code still isn’t robust if the operation failed. Just like cancellation, error reporting is supported through the same async operation. As well as using <b>AsyncStatus</b> to differentiate between Completed and Canceled, we also use it to determine failure of an async operation (i.e. <b>AsyncStatus.Error</b>). You can find the specific failure code in the <b>ErrorCode</b> property of the async operation.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">op.Completed = (info, status) =&gt;<br />            {<br />                <span style="color: #0000ff">if</span> (status == AsyncStatus.Completed)<br />                {<br />                    SyndicationFeed feed = info.GetResults();<br />                    UpdateAppWithFeed(feed);<br />                }<br />                <span style="color: #0000ff">else</span> <span style="color: #0000ff">if</span> (status == AsyncStatus.Canceled)<br />                {<br />                    <span style="color: #008000">// Operation canceled</span><br />                }<br />                <span style="color: #0000ff">else</span> <span style="color: #0000ff">if</span> (status == AsyncStatus.Error)<br />                {<br />                    <span style="color: #008000">// Error occurred, Report error</span><br />                }<br />            };<br /></pre>
</blockquote>
<p></div>
<h3>How it works: reporting progress with async primitives</h3>
<p>Some WinRT async operations provide progress notifications while they are running. You can use these notifications to report the current progress of the async operation to the user. </p>
<p>In WinRT, progress reporting is handled through the <b>IAsyncActionWithProgress&lt;TProgress&gt;</b> and <b>IAsyncOperationWithProgress&lt;TResult, TProgress&gt;</b> interfaces. Each interface contains a Progress event that you can use to get progress reports from the async operation. </p>
<p>The programming model to consume this is nearly identical to consuming the Completed event. In our example of retrieving syndication feeds, we can report how many bytes of the total amount have been retrieved:</p>
<p>&nbsp;</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">op = client.RetrieveFeedAsync(feedUri);<br /><br />            <span style="color: #0000ff">float</span> percentComplete = 0;<br />            op.Progress = (info, progress) =&gt;<br />            {<br />                percentComplete = progress.BytesRetrieved / <br />(<span style="color: #0000ff">float</span>)progress.TotalBytesToRetrieve;<br />            };<br /></pre>
</blockquote>
<p></div>
<p>In this case, the second parameter (<b>progress</b>) is of type <b>RetrievalProgress</b>. This type contains two parameters (<b>bytesRetrieved</b> and <b>totalBytesToRetrieve</b>) that are used to report our ongoing progress.</p>
<p><i></i></p>
<p>For deeper material (involving asynchronous programming in WinRT, or asynchrony in general), you can check out:</p>
<ul>
<li><a href="http://channel9.msdn.com/events/BUILD/BUILD2011/PLAT-203T" target="_blank">“Async Everywhere” talk</a><i> from the //Build conference</i>
<li><a href="http://blogs.msdn.com/b/ie/archive/2011/09/11/asynchronous-programming-in-javascript-with-promises.aspx" target="_blank">Asynchronous Programming in JavaScript with “Promises”</a>
<li><a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=19957" target="_blank">Task-Based Asynchronous Pattern</a>
<li><a href="http://www.microsoft.com/download/en/details.aspx?id=14058" target="_blank">Asynchrony in .NET</a> </li>
</ul>
<h3><b>In closing</b></h3>
<p>What’s interesting about asynchrony being so prevalent in WinRT is how it impacts the way you structure your code and architect your app. You start thinking about your app in a more loosely-connected way. If you have any feedback in this area, we would love to hear from you! Let us know by leaving a comment here or on the Dev Center forums. </p>
<p>We want your customers to love your Windows 8 apps. We want those apps to start alive with activity, and remain alive with activity. And we want you to more easily create those apps. We want you to be able to easily connect to social websites, store data in the cloud, work with files on the hard disk, communicate with other gadgets and devices, etc., while providing your customers with a great user experience.</p>
<p>&nbsp;</p>
<p>&#8211;Jason Olson</p>
<p>Program Manager, Windows</p>
<div style="clear:both;"></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10285647" width="1" height="1"><br />
<a rel="nofollow" href="http://blogs.msdn.com/b/windowsappdev/archive/2012/03/20/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime.aspx">Windows 8 app developer blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keeping apps fast and fluid with asynchrony in the Windows Runtime</title>
		<link>http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime</link>
		<comments>http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime/#comments</comments>
		<pubDate>Mon, 14 May 2012 16:27:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[For Developers]]></category>
		<category><![CDATA[Apps]]></category>
		<category><![CDATA[asynchrony]]></category>
		<category><![CDATA[Fast]]></category>
		<category><![CDATA[fluid]]></category>
		<category><![CDATA[Keeping]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime/</guid>
		<description><![CDATA[Human beings are asynchronous by nature, which directly affects how we expect apps to respond to us. The Windows Runtime (WinRT) has embraced this asynchrony as a first-class citizen in the building of fast and fluid Metro style apps. If you are building a Metro style app, you will need to write some asynchronous code]]></description>
			<content:encoded><![CDATA[<p>Human beings are asynchronous by nature, which directly affects how we expect apps to respond to us. The Windows Runtime (WinRT) has embraced this asynchrony as a first-class citizen in the building of fast and fluid Metro style apps. If you are building a Metro style app, you will need to write some asynchronous code at some point. In this blog post, we talk about why asynchronous programming is so prevalent in WinRT, and we’ll give you the basics on how to use it in your apps and some background on how it works.</p>
<h3><b>Fast and fluid apps must be responsive</b></h3>
<p>How many times have you been using a Windows app that stops responding, and you are presented with a greyed version of the app and the spinning donut? Without fail, it always seems to come at the worst possible time. Worse yet, you might end up losing a lot of hard work when this happens. </p>
<p>Users expect apps to be responsive to all interactions. When they use their favorite news reading app, they want to add news feeds, read news articles, save news articles, etc. They should be able to do all of these things even when the app is retrieving the latest articles from the Internet. </p>
<p>This becomes especially important when a user is interacting with your app using touch. Users notice when the app doesn’t “stick to your finger.” Even minor performance problems can degrade the user experience and break the fast and fluid feeling.</p>
<p>An app isn’t fast and fluid if it stops responding to user input. So why do apps stop responding? One major cause is that the app is synchronous; it is waiting for something else to finish (like getting data from the Internet) and can’t respond to your input.</p>
<p>Many modern apps connect to social websites, store data in the cloud, work with files on the hard disk, communicate with other gadgets and devices, etc. Some of these sources have unpredictable latencies, which makes creating fast and fluid apps challenging. Unless built correctly, apps spend more time waiting for the outside environment and less time responding to the user’s needs.</p>
<p>Addressing this connected world was a core principle when we started to design APIs for the Windows Runtime (WinRT). We felt it was important to provide an API surface that was powerful and led to fast and fluid apps by default. </p>
<p>To achieve those goals, we made many potentially I/O-bound APIs asynchronous in the Windows Runtime. These are the most likely candidates to visibly degrade performance if written synchronously (e.g. could likely take longer than 50 milliseconds to execute). This asynchronous approach to APIs sets you up to write code that is fast and fluid by default and promotes the importance of app responsiveness in Metro style app development. </p>
<p>For those of you unfamiliar with asynchronous patterns, think of asynchrony in WinRT as providing a callback number to somebody over the phone. You give the person the number to call you back, you hang up, and then you continue doing any other work you need to. When the person is ready to talk to you, they can call you back at the number you provided. This is the essence of how asynchrony works in WinRT.</p>
<p>To understand more about the asynchronous nature of WinRT, we will first look at how you can use these asynchronous APIs in a straightforward way. Then we will take an under the hood look at what async primitives WinRT has introduced (that the new language features build upon), and how they work. </p>
<h3><b>How to use it: new developer enhancements for asynchrony</b></h3>
<p>In the past, writing asynchronous code was difficult. Our teams building tools for Windows 8 Metro style apps made significant advancements in solving this problem in recent releases. In the .NET Framework 4.0, we introduced the <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx" target="_blank">Task Parallel Library</a>. Then the await keyword was introduced into C# and Visual Basic. C++ invested in technologies like the <a href="http://msdn.microsoft.com/en-us/library/dd492418.aspx" target="_blank">Parallel Patterns Library</a> (PPL). And JavaScript has great tools like <a href="http://blogs.msdn.com/b/ie/archive/2011/09/11/asynchronous-programming-in-javascript-with-promises.aspx" target="_blank">Promises</a>. </p>
<p>Each one of these technologies presents you with a straightforward way to write asynchronous code. By introducing a standard async pattern under the hood that all of these technologies use, we allow you to use these technologies when building Metro style apps regardless of which programming language you use. </p>
<p>In the case of your favorite news app, the code that remains responsive while retrieving news articles is quite simple using the <b>Windows.Web.Syndication.SyndicationClient</b> API. The call to RetrieveFeedAsync returns immediately. This is a great thing because the results might take a long time to come back from the Internet. In the meantime, the UI continues to interact with the user. </p>
<p>The code highlighted in yellow runs after the call to RetrieveFeedAsync is completed. You don’t need to think about all the “start again where you left off” plumbing. And the code is written in a straightforward way as if it was synchronous.</p>
<p align="center">
<div align="center">
<h5>JavaScript code to retrieve RSS feed asynchronously:</h5>
<p><span style="color: #0000ff"></span><br />
<blockquote>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">var</span> title;<br /><span style="color: #0000ff">var</span> feedUri = <span style="color: #0000ff">new</span> Windows.Foundation.Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">var</span> client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><br />client.retrieveFeedAsync(feedUri).<b>done</b>(<span style="background-color: #ffff00">function(feed) {<br />    title = feed.title.text;<br />});<br /></span></pre>
</blockquote>
</div>
<div>&nbsp;</div>
<h5 align="center">C# code to retrieve RSS feed asynchronously:</h5>
<div>
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">var feedUri = <span style="color: #0000ff">new</span> Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br />var client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><span style="background-color: #ffff00">var feed</span> = <b>await</b> client.RetrieveFeedAsync(feedUri);<br /><span style="background-color: #ffff00">var title = feed.Title.Text;</span></pre>
</blockquote>
</div>
<h4 align="left"></h4>
<div>
<h5 align="center">VB code to retrieve RSS feed asynchronously:</h5>
<p><span style="color: #0000ff"></span></p>
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">Dim</span> feedUri = <span style="color: #0000ff">New</span> Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">Dim</span> client = <span style="color: #0000ff">New</span> Windows.Web.Syndication.SyndicationClient();<br /><span style="background-color: #ffff00">Dim feed </span> = <b>Await</b> client.RetrieveFeedAsync(feedUri);<br /><span style="background-color: #ffff00">Dim title = feed.Title.Text;<br /></span></pre>
</blockquote>
</div>
<div>&nbsp;</div>
<h4 align="left"></h4>
<div>
<h5 align="center">C++ code to retrieve RSS feed asynchronously:</h5>
<p><span style="color: #0000ff"></span></p>
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">auto</span> feedUri = ref <span style="color: #0000ff">new</span> Windows::Foundation::Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">auto</span> client = ref <span style="color: #0000ff">new</span> Windows::Web::Syndication::SyndicationClient();<br /><br />task&lt;SyndicationFeed^&gt; retrieveTask(client-&gt;RetrieveFeedAsync(feedUri));<br />retrieveTask.<b>then</b>(<span style="background-color: #ffff00">[this] (SyndicationFeed^ feed) {<br />    this-&gt;title = feed-&gt;Title-&gt;Text;<br />});</span><br /></pre>
</blockquote>
</div>
<div>&nbsp;</div>
<h4 align="center"></h4>
<p>There is no mention of threads, context switching, dispatchers, etc. These new developer enhancements for writing asynchronous code will handle that for you. Code following the async API call is automatically called back in the same context that the original call was made. This means you can go ahead and update the UI with the results without worrying about getting back to the UI thread.</p>
<h3>How to use it: error handling</h3>
<p>Of course, API calls can fail (like losing network connectivity while retrieving RSS feeds). To be truly robust, we need to be resilient in the presence of errors. Using the async functionality in the languages makes handling errors more straightforward. The mechanism to do this varies based on the language.</p>
<p>For JavaScript, we recommend that you always end your Promise chains with <b>done</b>. This ensures that any exceptions captured in the promise chain are visible to the developer (i.e. reported in the error handler, or thrown). <b>Done</b> has the same signature as <b>then</b>. So to handle errors, you simply pass an error delegate into <b>done():</b></p>
<p>&nbsp;</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">var</span> title;<br /><span style="color: #0000ff">var</span> feedUri = <span style="color: #0000ff">new</span> Windows.Foundation.Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">var</span> client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><br />client.retrieveFeedAsync(feedUri).done(<span style="color: #0000ff">function</span>(feed) {<br />    title = feed.title.text;<br />}, <span style="color: #0000ff"><b>function</span>(error) {<br />    console.log(<span style="color: #006080">'an error occurred: '</span>);<br />    console.dir(error);<br />}</b>);</pre>
</blockquote>
<p></div>
<p>To handle the exception in C# or Visual Basic, you use a try/catch block just as you do with synchronous code today:</p>
<p>&nbsp;</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">var</span> title;<br /><span style="color: #0000ff">var</span> feedUri = <span style="color: #0000ff">new</span> Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">var</span> client = <span style="color: #0000ff">new</span> Windows.Web.Syndication.SyndicationClient();<br /><br /><span style="color: #0000ff"><b>try</span><br />{</b><br />    <span style="color: #0000ff">var</span> feed = await client.RetrieveFeedAsync(feedUri);<br />    title = feed.Title.Text;<br />}<br /><span style="color: #0000ff">catch</span> (Exception ex)<br />{<br />    <span style="color: #008000">// An exception occurred from the async operation</span><br />}</b></pre>
</blockquote>
<p></div>
<p>The most common method to use in C++ to handle async errors is to use another task-based continuation that throws the exceptions (you can find other methods for error handling in C++ in the topic <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx" target="_blank">Asynchronous Programming in C++</a> on Dev Center):</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">auto</span> feedUri = ref <span style="color: #0000ff">new</span> Windows::Foundation::Uri(<span style="color: #006080">"http://www.devhawk.com/rss.xml"</span>);<br /><span style="color: #0000ff">auto</span> client = ref <span style="color: #0000ff">new</span> Windows::Web::Syndication::SyndicationClient();<br /><br />task&lt;SyndicationFeed^&gt; retrieveTask(client-&gt;RetrieveFeedAsync(feedUri));<br />retrieveTask.then([<span style="color: #0000ff">this</span>] (SyndicationFeed^ feed) {<br />    <span style="color: #0000ff">this</span>-&gt;title = feed-&gt;Title-&gt;Text;<br />}).<b>then([] (task&lt;<span style="color: #0000ff">void</span>&gt; t) {<br />    <span style="color: #0000ff">try</span><br />    {<br />        t.get();<br />    <span style="color: #008000">// .get() didn't throw, so we succeeded</span><br />    }<br />    <span style="color: #0000ff">catch</span> (Exception^ ex)<br />    {<br />        <span style="color: #008000">// An error occurred</span><br />    }<br />})</b>;<br /></pre>
</blockquote>
<pre></pre>
<p></div>
<p>For more details on how to use these asynchronous improvements (including more scenarios like support cancellation and progress) see:<i></i></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464924.aspx" target="_blank">Asynchronous Programming in the Windows Runtime</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx" target="_blank">Asynchronous Programming in JavaScript</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx" target="_blank">Asynchronous Programming in C++</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh770843.aspx">Asynchronous Programming in .NET</a><i> on the Windows Dev Center</i>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700337.aspx" target="_blank">How to Handle Errors when using Promises in JavaScript</a><i> on the Windows Dev Center</i> </li>
</ul>
<h3><b>How it works: WinRT async primitives</b></h3>
<p>Async is very powerful, but it can appear that there is a lot of magic that happens here on your behalf. To demystify what is happening, let’s take a look at how asynchrony in WinRT works in a little more detail. Our first step is to investigate the primitives the model is built upon. Most of you won’t have to use these primitives at all (if you find a scenario where you have to do this, we would love to hear the feedback).</p>
<p>Starting with our C# code, let’s look at the actual return type of <b>RetrieveFeedAsync</b> (shown here in C# Intellisense): </p>
<p>&nbsp;<a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3005.intellisense_5F00_17BE4799.jpg" rel="lightbox[1280]" title="Intellisense displayed for RetrieveFeedAsync method"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Intellisense displayed for RetrieveFeedAsync method" border="0" alt="Intellisense displayed for RetrieveFeedAsync method" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/2084.intellisense_5F00_thumb_5F00_373D71A1.jpg" width="592" height="99"></a> <br />&nbsp;<em>Figure 1. Intellisense displayed for RetrieveFeedAsync method</em></p>
<p><b>RetrieveFeedAsync</b> returns an <b>IAsyncOperationWithProgress</b> interface. <b>IAsyncOperationWithProgress</b> is one of 5 interfaces that define the core asynchronous programming surface for WinRT: <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.foundation.iasyncinfo.aspx" target="_blank">IAsyncInfo</a>, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.foundation.iasyncaction.aspx" target="_blank">IAsyncAction</a>, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br206581.aspx" target="_blank">IAsyncActionWithProgress</a>, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br206598.aspx" target="_blank">IAsyncOperation</a>, and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br206594.aspx" target="_blank">IAsyncOperationWithProgress</a>. </p>
<p>The core interface that the WinRT async model is built on is <b>IAsyncInfo</b>. This core interface defines properties of an async operation like current status, the ability to cancel the operation, the error of a failed operation, etc. </p>
<p>As we mentioned earlier, async operations can return results. Async operations in WinRT can also report progress as they are running. The other 4 async interfaces above (<b>IAsyncAction</b>, <b>IAsyncActionWithProgress</b>, <b>IAsyncOperation</b>, and <b>IAsyncOperationWithProgress</b>) define different combinations of results and progress. </p>
<p>&nbsp;</p>
<p><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/7870.Tableshowingdifferentcombinationsofresultsandprogress_5F00_6A66160E.jpg" rel="lightbox[1280]" title="Table showing different combinations of results and progress"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Table showing different combinations of results and progress" border="0" alt="Table showing different combinations of results and progress" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8551.Tableshowingdifferentcombinationsofresultsandprogress_5F00_thumb_5F00_6346D996.jpg" width="640" height="211"></a>&nbsp;&nbsp;&nbsp; <br /><em>Figure 2. Different combinations of results and progress</em></p>
<p>Providing core async primitives in the Windows Runtime enables C#, Visual Basic, C++, and JavaScript to project WinRT async operations in a familiar way to you. </p>
<p><b>Note: The move from cold start to hot start</b></p>
<p>In the Windows 8 Developer Preview released at //build, all async operations in WinRT were started cold. They didn’t start running immediately. They had to be explicitly started by the developer or implicitly started using the async features in C#, Visual Basic, JavaScript, or C++. We received feedback from several sources that this wasn’t intuitive and could cause pain and confusion.</p>
<p>In the Windows 8 Consumer Preview release, you will notice that we removed the Start() method from the WinRT async primitives. Now, our async operations are all started hot. So, the async method launched the operation before returning it to the caller. </p>
<p>This is just one of many changes that you’ll find in the Consumer Preview where we’ve fine-tuned the developer platform based on all the great feedback you have given us.</p>
<p><b>How it works: results, cancellation, and errors with async primitives</b></p>
<p>An async operation starts in the Started state and can progress to one of three other states: Canceled, Completed, and Error. The current state of an async operation is reflected in the Status property of the async operation (represented by the <b>AsyncStatus</b> enum type). </p>
<p>The first thing we do with an async operation is wire up a completed handler. From within the completed handler, we can get the results and use them.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">IAsyncOperationWithProgress&lt;SyndicationFeed, RetrievalProgress&gt; op;<br />            op = client.RetrieveFeedAsync(feedUri);<br /><br />            op.Completed = (info, status) =&gt;<br />            {<br />                SyndicationFeed feed = info.GetResults();<br />                UpdateAppWithFeed(feed);<br />            };<br /></pre>
</blockquote>
<p></div>
<p>Sometimes you may want to cancel an operation. You can do this by calling the Cancel method on the async operation.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">IAsyncOperationWithProgress&lt;SyndicationFeed, RetrievalProgress&gt; op;<br />op = client.RetrieveFeedAsync(feedUri);<br /><b>op.Cancel();</b><br /></pre>
<p></p></blockquote>
</div>
<p>The Completed handler is always called for an async operation regardless of whether it was completed, canceled, or resulted in an error. Call <b>GetResults</b> only when the async operation was completed (e.g. not when the operation is canceled or ends in an error). You can determine this by inspecting the status parameter.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">IAsyncOperationWithProgress&lt;SyndicationFeed, RetrievalProgress&gt; op;<br />            op = client.RetrieveFeedAsync(feedUri);<br />            op.Cancel();<br /><br />            op.Completed = (info, status) =&gt;<br />            {<br />                <span style="color: #0000ff"><b>if</span> (status ==</b> AsyncStatus.<b>Completed)</b><br />                {<br />                    SyndicationFeed feed = info.GetResults();<br />                    UpdateAppWithFeed(feed);<br />                }<br />                <span style="color: #0000ff"><b>else</span> <span style="color: #0000ff">if</span> (status ==</b> AsyncStatus.<b>Canceled)</b><br />                {<br />                    <span style="color: #008000">// Operation canceled</span><br />                }<br />            };<br /></pre>
</blockquote>
<pre></pre>
<p></div>
<p>This code still isn’t robust if the operation failed. Just like cancellation, error reporting is supported through the same async operation. As well as using <b>AsyncStatus</b> to differentiate between Completed and Canceled, we also use it to determine failure of an async operation (i.e. <b>AsyncStatus.Error</b>). You can find the specific failure code in the <b>ErrorCode</b> property of the async operation.</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">op.Completed = (info, status) =&gt;<br />            {<br />                <span style="color: #0000ff">if</span> (status == AsyncStatus.Completed)<br />                {<br />                    SyndicationFeed feed = info.GetResults();<br />                    UpdateAppWithFeed(feed);<br />                }<br />                <span style="color: #0000ff">else</span> <span style="color: #0000ff">if</span> (status == AsyncStatus.Canceled)<br />                {<br />                    <span style="color: #008000">// Operation canceled</span><br />                }<br />                <span style="color: #0000ff">else</span> <span style="color: #0000ff">if</span> (status == AsyncStatus.Error)<br />                {<br />                    <span style="color: #008000">// Error occurred, Report error</span><br />                }<br />            };<br /></pre>
</blockquote>
<p></div>
<h3>How it works: reporting progress with async primitives</h3>
<p>Some WinRT async operations provide progress notifications while they are running. You can use these notifications to report the current progress of the async operation to the user. </p>
<p>In WinRT, progress reporting is handled through the <b>IAsyncActionWithProgress&lt;TProgress&gt;</b> and <b>IAsyncOperationWithProgress&lt;TResult, TProgress&gt;</b> interfaces. Each interface contains a Progress event that you can use to get progress reports from the async operation. </p>
<p>The programming model to consume this is nearly identical to consuming the Completed event. In our example of retrieving syndication feeds, we can report how many bytes of the total amount have been retrieved:</p>
<p>&nbsp;</p>
<div id="codeSnippetWrapper">
<blockquote><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">op = client.RetrieveFeedAsync(feedUri);<br /><br />            <span style="color: #0000ff">float</span> percentComplete = 0;<br />            op.Progress = (info, progress) =&gt;<br />            {<br />                percentComplete = progress.BytesRetrieved / <br />(<span style="color: #0000ff">float</span>)progress.TotalBytesToRetrieve;<br />            };<br /></pre>
</blockquote>
<p></div>
<p>In this case, the second parameter (<b>progress</b>) is of type <b>RetrievalProgress</b>. This type contains two parameters (<b>bytesRetrieved</b> and <b>totalBytesToRetrieve</b>) that are used to report our ongoing progress.</p>
<p><i></i></p>
<p>For deeper material (involving asynchronous programming in WinRT, or asynchrony in general), you can check out:</p>
<ul>
<li><a href="http://channel9.msdn.com/events/BUILD/BUILD2011/PLAT-203T" target="_blank">“Async Everywhere” talk</a><i> from the //Build conference</i>
<li><a href="http://blogs.msdn.com/b/ie/archive/2011/09/11/asynchronous-programming-in-javascript-with-promises.aspx" target="_blank">Asynchronous Programming in JavaScript with “Promises”</a>
<li><a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=19957" target="_blank">Task-Based Asynchronous Pattern</a>
<li><a href="http://www.microsoft.com/download/en/details.aspx?id=14058" target="_blank">Asynchrony in .NET</a> </li>
</ul>
<h3><b>In closing</b></h3>
<p>What’s interesting about asynchrony being so prevalent in WinRT is how it impacts the way you structure your code and architect your app. You start thinking about your app in a more loosely-connected way. If you have any feedback in this area, we would love to hear from you! Let us know by leaving a comment here or on the Dev Center forums. </p>
<p>We want your customers to love your Windows 8 apps. We want those apps to start alive with activity, and remain alive with activity. And we want you to more easily create those apps. We want you to be able to easily connect to social websites, store data in the cloud, work with files on the hard disk, communicate with other gadgets and devices, etc., while providing your customers with a great user experience.</p>
<p>&nbsp;</p>
<p>&#8211;Jason Olson</p>
<p>Program Manager, Windows</p>
<div style="clear:both;"></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10285647" width="1" height="1"><br />
<a rel="nofollow" href="http://blogs.msdn.com/b/windowsappdev/archive/2012/03/20/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime.aspx">Windows 8 app developer blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.windows8tricks.net/2012/05/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Introduction to Windows Runtime (WinRT) (@mbrit Technical Briefings) Reviews</title>
		<link>http://www.windows8tricks.net/2012/02/an-introduction-to-windows-runtime-winrt-mbrit-technical-briefings-reviews/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=an-introduction-to-windows-runtime-winrt-mbrit-technical-briefings-reviews</link>
		<comments>http://www.windows8tricks.net/2012/02/an-introduction-to-windows-runtime-winrt-mbrit-technical-briefings-reviews/#comments</comments>
		<pubDate>Sun, 19 Feb 2012 18:42:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Windows 8 Books]]></category>
		<category><![CDATA[@mbrit]]></category>
		<category><![CDATA[Briefings]]></category>
		<category><![CDATA[Introduction]]></category>
		<category><![CDATA[Reviews]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[WinRT]]></category>

		<guid isPermaLink="false">http://www.windows8tricks.net/2012/02/an-introduction-to-windows-runtime-winrt-mbrit-technical-briefings-reviews/</guid>
		<description><![CDATA[An Introduction to Windows Runtime (WinRT) (@mbrit Technical Briefings) Want to understand more about the new programming model for Windows? Windows Runtime, or Win32, is the reboot of the Win32 API for Windows. WinRT is the only way to build Metro-style apps for the Windows 8 operating system. *** Money-back guarantee. We&#8217;ll refund you if]]></description>
			<content:encoded><![CDATA[<h3><a href="http://www.amazon.com/Introduction-Windows-Technical-Briefings-ebook/dp/B00749HXV4%3FSubscriptionId%3DAKIAI4YSUKDIFSJMBPDA%26tag%3Dwin707-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00749HXV4" rel="nofollow">An Introduction to Windows Runtime (WinRT) (@mbrit Technical Briefings)</a></h3>
<p><a href="http://www.amazon.com/Introduction-Windows-Technical-Briefings-ebook/dp/B00749HXV4%3FSubscriptionId%3DAKIAI4YSUKDIFSJMBPDA%26tag%3Dwin707-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00749HXV4" rel="nofollow"><img style="float:left;margin: 0 20px 10px 0;" src="http://ecx.images-amazon.com/images/I/51e9ZRP1WtL._SL160_.jpg" /></a></p>
<p>Want to understand more about the new programming model for Windows? Windows Runtime, or Win32, is the reboot of the Win32 API for Windows. WinRT is the only way to build Metro-style apps for the Windows 8 operating system.</p>
<p>*** Money-back guarantee. We&#8217;ll refund you if you tell us you got no value from this book. ***</p>
<p>In this ebook, you&#8217;ll learn exactly what WinRT is and what impact it’s going to have on Windows developers.</p>
<p>This ebook is kept up-to-date when new</p>
<p><div style="float:right;"><a href="http://www.amazon.com/Introduction-Windows-Technical-Briefings-ebook/dp/B00749HXV4%3FSubscriptionId%3DAKIAI4YSUKDIFSJMBPDA%26tag%3Dwin707-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00749HXV4" rel="nofollow"><img src="http://www.windows8tricks.net/wp-content/plugins/WPRobot3/images/buynow-big.gif" /></a></div>
<p><strong>Price: </strong>
</p>
<p>More <a href="http://www.windows8tricks.net/category/windows-8-books/">Windows 8 Products</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.windows8tricks.net/2012/02/an-introduction-to-windows-runtime-winrt-mbrit-technical-briefings-reviews/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reducing runtime memory in Windows 8</title>
		<link>http://www.windows8tricks.net/2012/01/reducing-runtime-memory-in-windows-8/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=reducing-runtime-memory-in-windows-8</link>
		<comments>http://www.windows8tricks.net/2012/01/reducing-runtime-memory-in-windows-8/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 12:03:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[Reducing]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.windows8tricks.net/2012/01/reducing-runtime-memory-in-windows-8/</guid>
		<description><![CDATA[Fundamentals such as memory usage represent a key engineering tenet of Windows 8. In building Windows 8 we set out to significantly reduce the overall runtime memory requirements of the core system. This is always good for everyone and especially in a world where people want to run more and more apps at the same]]></description>
			<content:encoded><![CDATA[<blockquote><p><i>Fundamentals such as memory usage represent a key engineering tenet of Windows 8. In building Windows 8 we set out to significantly reduce the overall runtime memory requirements of the core system. This is always good for everyone and especially in a world where people want to run more and more apps at the same time or run on systems with only 1 or 2GB of memory. The laptop we talk about in this post is the exact same one we talked about at the Windows 7 PDC in 2008 – an off-the-shelf, first-generation, ATOM-based netbook with 1GB of memory. </i><i>This post details our efforts around memory footprint and was authored by Bill Karagounis, the group program manager of our Performance team. &#8211;Steven</i></p>
</blockquote>
<p>The runtime memory usage of Windows 8 is an important factor in determining the Windows 8 system requirements, as well as the broadened spectrum of devices that will host Windows 8. As you know, we’re delivering the complete Windows 8 experience on SoC-based devices characterized by low power consumption. This makes it even more important to leave lots of memory available for multiple concurrent apps and to sustain the overall responsiveness of devices.</p>
<p>Something that might not be obvious is that minimizing memory usage on low-power platforms can prolong battery life. Huh? In any PC, RAM is constantly consuming power. If an OS uses a lot of memory, it can force device manufacturers to include more physical RAM. The more RAM you have on board, the more power it uses, the less battery life you get. Having additional RAM on a tablet device can, in some instances, shave days off the amount of time the tablet can sit on your coffee table looking off but staying fresh and up to date.</p>
<h3>Memory usage goals</h3>
<p>Our goal with Windows 8 from the beginning was to ship with the same <a href="http://windows.microsoft.com/en-us/windows7/products/system-requirements" target="_blank">system requirements as Windows 7</a>. We know if we do even better that there are more resources for apps, even if we keep the published requirements the same. It is fun to think about what the &quot;low end&quot; hardware looked like in 2009 and how you can&#8217;t even find things like 256MB memory modules anymore. We wanted to ensure that people running on Windows 7-era hardware would have the option to easily upgrade their existing machines to Windows 8 and take advantage of the functionality it has to offer. We also expect that many machines that predate the Windows 7 release will run Windows 8 based on the experiences we’ve had with older machines we intentionally keep in our performance test infrastructure.</p>
<p>An important task for Windows 8 was to make room for new functionality while looking for opportunities to reduce the memory consumed by existing functionality and consumed across the board. Windows 8 is tracking well towards meeting the goal we set ourselves.</p>
<h3>Task Manager memory use comparison</h3>
<p>The easiest way to make a ballpark comparison of Windows 8 vs. Windows 7 memory use is to install both operating systems on a 1GB RAM machine (minimum OS RAM requirement) and compare them when they’ve been rebooted multiple times, and then idled for a while.</p>
<p>The Windows Task Manager contains the main view of system memory through its “In Use” statistic (described in detail in <a href="http://msdn.microsoft.com/en-us/windows/hardware/gg463425.aspx" target="_blank">this doc</a>). The below graphics compare memory consumption on Steven’s 3+ year old netbook that he was using at the //build/ keynote recently, running Windows 7 at idle, and then with the same machine running Windows 8.</p>
<p align="center"><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-29-43-metablogapi/5543.Figure_2D00_1_2D002D002D00_Memory_2D00_usage_2D00_in_2D00_Windows_2D00_7_2D00_SP1_5F00_6319A771.png" target="_blank" rel="lightbox[232]" title="Figure 1 - Memory usage in Windows 7 SP1"><img style="background-image: none; border-right-width: 0px; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Figure 1 - Memory usage in Windows 7 SP1" border="0" alt="Windows 7 Task Manager. CPU usage: 5%, Memory: 404 MB" src="http://www.windows8tricks.net/wp-content/uploads/2012/02/8270.Figure_2D00_1_2D002D002D00_Memory_2D00_usage_2D00_in_2D00_Windows_2D00_7_2D00_SP1_5F00_thumb_5F00_30B5D3F2.png" width="408" height="553" /></a><em>Figure 1 – Memory usage in Windows 7 SP1</em></p>
<p align="center"><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-29-43-metablogapi/4073.Figure_2D00_2_2D002D002D00_Memory_2D00_usage_2D00_in_2D00_Windows_2D00_8_5F00_7BA944C1.png" target="_blank" rel="lightbox[232]" title="Figure 2 - Memory usage in Windows 8"><img style="background-image: none; border-right-width: 0px; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Figure 2 - Memory usage in Windows 8" border="0" alt="Windows 8 Task Manager. CPU usage: 1%, Memory: 281 MB" src="http://www.windows8tricks.net/wp-content/uploads/2012/02/0172.Figure_2D00_2_2D002D002D00_Memory_2D00_usage_2D00_in_2D00_Windows_2D00_8_5F00_thumb_5F00_3049A0FD.png" width="404" height="553" /></a><em>Figure 2 – Memory usage in Windows 8</em></p>
<p>The specific hardware making up a machine, memory use of drivers, and even uptime can cause variability, so memory results will be different on different machines (or even the same machine at different times). As you can see though, Windows 8 is doing well relative to Windows 7.</p>
<p>For a bit of extra fun on a test machine, go to device manager and disable your display adapter (unload the graphics driver). You’d never run your machine this way but this does give you an even closer approximation of the memory use of Windows itself. With a disabled graphics driver, the machine above gets under 200MB after idling for a while.</p>
<p>NOTE: For Windows 8, a clean install also contains the extended Windows Defender technology, which, for the first time incorporates complete antimalware functionality – also optimized for memory and resource use per <a href="http://blogs.msdn.com/b/b8/archive/2011/09/15/protecting-you-from-malware.aspx" target="_blank">Jason’s blog about protecting you from malware</a>. (This functionality does not exist on a clean install of Windows 7 where we would recommend that you add security software).</p>
<h4>Making room in Windows 8</h4>
<p>We made hundreds of specific changes to minimize OS memory use in Windows 8. I’m going to call out a few specific areas that resulted in substantial memory savings.</p>
<h4>Memory combining</h4>
<p>When assessing the contents of RAM in a typical running PC, many parts of memory have the same content. The redundant copies of data across system RAM present an opportunity to reduce the memory footprint even for services and OS components.</p>
<p>How can this happen? Applications will sometimes allocate memory for future use and will initialize it all to the same value. The application may never actually use the memory as it may be there in anticipation of functionality that is the user never invokes. If multiple running applications are doing this at the same time, redundant copies of memory are in the system.</p>
<p>Memory combining is a technique in which Windows efficiently assesses the content of system RAM during normal activity and locates duplicate content across all system memory. Windows will then free up duplicates and keep a single copy. If the application tries to write to the memory in future, Windows will give it a private copy. All of this happens under the covers in the memory manager, with no impact on applications. This approach can liberate 10s to 100s of MBs of memory (depending on how many applications are running concurrently).</p>
<h4>Service changes and reductions</h4>
<p>OS services configured to run all the time are a significant source of ambient memory use. When assessing the set of OS services during Windows 8 planning, we decided to remove a number of them (13), move a different set of services to “manual” start, and also made some of the “always running” services move to a “<a href="http://msdn.microsoft.com/en-us/windows/hardware/gg463428" target="_blank">start on demand</a>” model. This is where a “trigger” in the OS (like device arrival or the availability of a network address) causes the following to occur:</p>
<ol>
<li>The service starts. </li>
<li>The service does its thing (whatever that happens to be). </li>
<li>It hangs around for a while to make sure there isn’t anything else to do, and </li>
<li>The service goes away. </li>
</ol>
<p>You’ll notice that Plug and Play, Windows Update, and the the user mode driver framework service are all trigger-started in Windows 8, in contrast to Windows 7, where these services were always running.</p>
<p>Of course we have added a ton of new functionality (and new code) to Windows 8. Some of this new functionality is packaged in the form of new services. Of these new services, two are auto-started; all others are manual or trigger-started.</p>
<h4>Doing the same job with less memory</h4>
<p>As Windows executes applications and performs its own system housekeeping, program files and data are loaded off the disk into main memory. During Windows 7 and Windows 8 development to date, we’ve analyzed the pieces (pages) of memory during normal execution and how often they were referenced. The idea here is that if you’re going to pay the price for allocating a piece of memory, you’d better be using it (referencing it) often. If you’re not referencing that memory often but need it, consolidate it with something else.</p>
<p>Shortly after we shipped Windows 7, we applied a similar technique to several of the low level components of Windows dating back to the early days of NT (early 1990s). The work included re-architecture of code and changing data structures to completely separate “hot” parts of memory (frequently referenced) from “cold” parts. By densely consolidating the hot items, we brought down the overall runtime memory cost.</p>
<p>Given the nature of the changes (low-level OS), we wanted to get the work done as early as possible in the schedule to get ample runtime on the changes. To date, these changes have been in place on Windows 8 for almost 2 years with thousands of Microsoft employees using the product to get their daily jobs done. And we’ve seen consistent results showing memory usage reduced by tens of MB on an average machine.</p>
<h4>Lazy initialization of the “desktop”</h4>
<p>Back in June, you saw Steven and Julie introduce the Metro style UI for the first time. We expect many people using tablets to spend a lot of time in that environment, typically using Metro style apps. As part of that demonstration, we also showed that for Windows 8, you can also bring forward your existing applications and use them in the very familiar desktop environment.</p>
<p>From a memory perspective, we’ve taken advantage of the fact that there will be some set of devices on which users will stay in the immersive, Metro style UI almost all the time. In this instance, Windows 8 will only initialize OS components unique to the desktop environment when necessary. This is another source of memory savings, approximately 23MB right now. (Note that Task Manager runs in the desktop, so the memory numbers shown above include its cost).</p>
<h4>More granular prioritization of memory</h4>
<p>Windows 8 has a better scheme for the prioritization of memory allocations made by applications and system components. This means that Windows can make better decisions about what memory to keep around and what memory to remove sooner.</p>
<p>For example, antivirus programs (AV) do various checks on files when they are being opened by other programs. The memory that the AV program allocates to check virus signatures is usually a one-time allocation (it is unlikely that specific memory will be needed again). On Windows 7, the memory is treated as if it had the same priority in the system as other memory (say, memory allocated by a running instance of Microsoft Excel). If memory became scarce, Windows 7 could end up removing the memory that helps another running application (like Excel) stay responsive for the user, which wouldn’t be the best choice for system responsiveness in this case.</p>
<p>In Windows 8, any program has the ability to allocate memory as “low priority.” This is an important signal to Windows that if there is memory pressure, Windows can remove this low priority memory to make space, and it doesn’t affect other memory required to sustain the responsiveness of the system.</p>
<p>To wrap up, I’ve called out our philosophy and approach to reducing memory usage in Windows 8. You’ve seen some sample results and I’ve just scratched the surface on some of the engineering work done to date in this area. One thing I haven’t discussed at all is the Windows 8 application model, and process lifecycle changes made to make new Windows 8 apps more “memory friendly.” Look out for this in the <a href="http://www.buildwindows.com/" target="_blank">//build/</a> content and in future blog posts, as it’s also a really important part of the story of reimagining Windows.</p>
<p>We’ve already come a long way but we’re not done.</p>
<p>&#8211;Bill Karagounis</p>
<div style="clear:both;"></div>
<p><img src="" width="1" height="1"><br />
<a rel="nofollow" href="http://blogs.msdn.com/b/b8/archive/2011/10/07/reducing-runtime-memory-in-windows-8.aspx">Building Windows 8</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.windows8tricks.net/2012/01/reducing-runtime-memory-in-windows-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
