<?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>Mindscape Blog &#187; General</title>
	<atom:link href="http://www.mindscapehq.com/blog/index.php/category/general/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mindscapehq.com/blog</link>
	<description>The official blog of Mindscape</description>
	<lastBuildDate>Thu, 16 May 2013 08:55:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<item>
		<title>Get an awesome Raygun T-shirt!</title>
		<link>http://www.mindscapehq.com/blog/index.php/2013/03/05/get-an-awesome-raygun-t-shirt/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2013/03/05/get-an-awesome-raygun-t-shirt/#comments</comments>
		<pubDate>Tue, 05 Mar 2013 23:09:10 +0000</pubDate>
		<dc:creator>hilary</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=6445</guid>
		<description><![CDATA[Robbie the Robot wants you! To try out our newest product for tracking and fixing errors - Raygun.io! Sign up for a FREE 30 day trial, and find out how Raygun makes error collecting, reporting and management automatic and easy. Then, if you blog about your experience with Raygun (and your honest experience at that), we&#8217;d [...]]]></description>
				<content:encoded><![CDATA[<p><strong>Robbie the Robot wants you!</strong></p>
<p style="text-align: center;"><a href="http://raygun.io/" rel="attachment wp-att-6463"><img class="aligncenter size-full wp-image-6463" alt="Robot" src="http://www.mindscapehq.com/blog/wp-content/uploads/2013/03/Robot.png" width="240" height="240" /></a></p>
<p><strong>To try out our newest product for tracking and fixing errors</strong> - <strong><a href="http://raygun.io">Raygun.io</a>!</strong></p>
<p><strong><a href="http://raygun.io/">Sign up for a FREE 30 day trial</a></strong>, and find out how Raygun makes error collecting, reporting and management automatic and easy.</p>
<p><a href="http://raygun.io/"><img class="aligncenter size-full wp-image-6414" alt="Sign up to raygun for a free trial" src="http://www.mindscapehq.com/blog/wp-content/uploads/2013/02/RaygunSignup.png" width="718" height="52" /></a></p>
<p>Then, if you blog about your experience with Raygun (and your honest experience at that), we&#8217;d love to send you <strong>your very own Raygun T-shirt </strong>(anywhere in the world).</p>
<p><center></p>
<div id="attachment_6449" class="wp-caption aligncenter" style="width: 612px"><a href="http://raygun.io/" rel="attachment wp-att-6449"><img class=" wp-image-6449 " alt="Double-T-shirts" src="http://www.mindscapehq.com/blog/wp-content/uploads/2013/02/Double-T-shirts1.jpg" width="602" height="458" /></a><p class="wp-caption-text">Like these cool dudes are wearing!</p></div>
<p></center><strong>They come in lady sizes too!</strong></p>
<p><center></p>
<div id="attachment_6471" class="wp-caption aligncenter" style="width: 528px"><a href="http://raygun.io/"><img class=" wp-image-6471 " alt="Hilary-raygun-tshirt" src="http://www.mindscapehq.com/blog/wp-content/uploads/2013/03/Hilary-raygun-tshirt.jpg" width="518" height="509" /></a><p class="wp-caption-text">I&#8217;m an error blasting machine.</p></div>
<p></center></p>
<p style="text-align: left;">So if you would like to do a blog review of your experience with the mighty Raygun, <strong><a href="http://raygun.io/">sign up here for your free trial</a></strong>, and email <strong>hilary@mindscape.co.nz to grab one of these rad T-shirts while we still have &#8216;em!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2013/03/05/get-an-awesome-raygun-t-shirt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nightly news, 8 Feb 2013</title>
		<link>http://www.mindscapehq.com/blog/index.php/2013/02/07/nightly-news-8-feb-2013/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2013/02/07/nightly-news-8-feb-2013/#comments</comments>
		<pubDate>Fri, 08 Feb 2013 00:53:18 +0000</pubDate>
		<dc:creator>Jeremy Boyd</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=6394</guid>
		<description><![CDATA[LightSpeed Add constructor which allows user to specify the list of stop words used by the Lucene analyzer Web Workbench Intelliense for Less mixins is now correctly triggered when in a CSS property context WPF Diagrams Added DiagramConnectionPointBase.HasConnections property (details) The drag-panning user operation now respects the AllowInfiniteScroll property. (details) Resolved a diagram scrolling bug. [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://schneems.com/post/42508340989/open-source-in-your-inbox-code-triage"><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2012/05/DeveloperNotes211.png" alt="" title="" width="344" height="64" class="alignleft size-full wp-image-5007" /></a></p>
<p><strong>LightSpeed</strong></p>
<ul>
<li>Add constructor which allows user to specify the list of stop words used by the Lucene analyzer</li>
</ul>
<p><strong>Web Workbench</strong></p>
<ul>
<li>Intelliense for Less mixins is now correctly triggered when in a CSS property context</li>
</ul>
<p><strong>WPF Diagrams</strong></p>
<ul>
<li>Added DiagramConnectionPointBase.HasConnections property<br />
 <a href="http://www.mindscapehq.com/forums/thread/571382">(details)</a></li>
<li>The drag-panning user operation now respects the AllowInfiniteScroll property.<br />
 <a href="http://www.mindscapehq.com/forums/thread/451392#572112">(details)</a></li>
<li>Resolved a diagram scrolling bug.<br />
 <a href="http://www.mindscapehq.com/forums/thread/575313">(details)</a></li>
<li>Resolved a critical selection bug.<br />
 <a href="http://www.mindscapehq.com/forums/thread/577731">(details)</a></li>
</ul>
<p><strong>WPF Elements</strong></p>
<ul>
<li>Resolved a rendering bug in the DataGrid caused by changing the visibility while a custom cell has focus.<br />
 <a href="http://www.mindscapehq.com/forums/thread/576144">(details)</a></li>
<li>Added DataGrid.AutoColumnWidthBehavior property.<br />
 <a href="http://www.mindscapehq.com/forums/thread/573612">(details)</a></li>
<li>Resolved a minor charting selection bug.<br />
 <a href="http://www.mindscapehq.com/forums/thread/542385#569862">(details)</a></li>
<li>Added Chart.CanToggleSelection property.<br />
 <a href="http://www.mindscapehq.com/forums/thread/542385#569862">(details)</a></li>
<li>Added Chart.CanDeselectOnClickNothing property.<br />
 <a href="http://www.mindscapehq.com/forums/thread/542385#569862">(details)</a></li>
<li>Added Chart.IsRightClickSelectionEnabled property.<br />
 <a href="http://www.mindscapehq.com/forums/thread/542385#569862">(details)</a></li>
<li>Resolved a DataGrid auto column width issue.<br />
 <a href="http://www.mindscapehq.com/forums/thread/573612#578314">(details)</a></li>
<li>Added DataGridColumn.MaxAutoWidth property.<br />
 <a href="http://www.mindscapehq.com/forums/thread/573612#578314">(details)</a></li>
<li>Added DataGrid.CanAutoSizeColumnHeaders property.<br />
 <a href="http://www.mindscapehq.com/forums/thread/573612#578314">(details)</a></li>
<li>DataPoint selection logic now respects the IsRightClickSelectionEnabled and CanToggleSelection properties.<br />
 <a href="http://www.mindscapehq.com/forums/thread/542385#581307">(details)</a></li>
</ul>
<p>As usual the <a href="http://www.mindscapehq.com/downloads/">free editions of the nightly builds are available right now from the downloads page</a>, and the <a href="http://www.mindscapehq.com/store/myaccount">full editions from the store</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2013/02/07/nightly-news-8-feb-2013/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Metro Elements &#8211; Amazing new financial charts for Windows Store apps</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/12/09/metro-elements-amazing-new-financial-charts-for-windows-store-apps/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/12/09/metro-elements-amazing-new-financial-charts-for-windows-store-apps/#comments</comments>
		<pubDate>Mon, 10 Dec 2012 04:47:57 +0000</pubDate>
		<dc:creator>CallumG</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=6200</guid>
		<description><![CDATA[Here at Mindscape we&#8217;re excited about the upcoming release of some great new tools and control suites. One of these is Metro Elements for Windows Store apps, and those of you that are participating in its beta will know it&#8217;s looking pretty great. I&#8217;m particularly pleased with the new financial chart controls; you get two [...]]]></description>
				<content:encoded><![CDATA[<p>Here at Mindscape we&#8217;re excited about the upcoming release of some great new tools and control suites. One of these is <strong>Metro Elements</strong> for Windows Store apps, and those of you that are participating in its beta will know it&#8217;s looking pretty great. I&#8217;m particularly pleased with the new financial chart controls; you get two great controls ready to display market data with little initial configuration needed. To see these in action, you can check out the Youtube video here:</p>
<p><a href="http://www.youtube.com/watch?v=1atwZgpqF3A">http://www.youtube.com/watch?v=1atwZgpqF3A</a></p>
<p>One is the Candlestick Chart, the other is the Stock Chart, also referred to as an Open-High-Low-Close chart. They both display points with that data (OHLC), while varying in their presentation &#8211; so you get to choose the type that best suits your client&#8217;s data and use cases. The Candlestick chart displays the area between the open and close prices as a shaded box.</p>
<p>It takes just a few quick steps to place one of these charts in your Windows Store app. In your Page&#8217;s Xaml, create an instance of a Chart, along with either the StockSeries or CandlestickSeries (I&#8217;ll be using the latter) nested inside it:</p>
<p><code>&lt;ch:Chart&gt;<br />
&lt;ms:CandlestickSeries ItemsSource="{Binding Data}" /&gt;<br />
&lt;/ch:Chart&gt;</code></p>
<p>As is standard, we can set the ItemsSource to bind to a Collection property on the DataContext. Metro Elements provides a handy helper object to represent OHLC data points, and we can use that to get our Candlestick chart up and running quickly. The type is StockDataPoint, which resides in Mindscape.MetroElements.Charting. The constructor signature for it looks like this:</p>
<p><code>public StockDataPoint(DateTime date, double open, double high, double low, double close)</code></p>
<p>You only need to provide a DataTime along the OHLC values and the CandlestickSeries/StockSeries will display your data immediately. If, however, you already have your own model and data structure for representing OHLC, binding to that is also easy. Firstly set the ItemsSource to the Collection holding your custom OHLC structures. Then, just set the follow properties on CandlestickSeries to specify which model properties contain the relevant data: XBinding, YBinding, LowBinding, HighBinding, OpenBinding, CloseBinding.</p>
<p><strong>Styling the points</strong></p>
<p>You may want to style the points depending on how the point performed that day &#8211; if the close is lower than the open, then color the point red, for instance. That&#8217;s as easy as providing the desired color to the series:</p>
<p><code>&lt;ms:CandlestickSeries ItemsSource="{Binding Data}" NegativeSeriesBrush="#FF0000" /&gt;</code></p>
<p>Or, if you want to completely customize the style of the negative or positive points, you can too. This is accomplished by setting NegativeStyle or PositiveStyle.</p>
<p>One of the best features about our Chart control is how modular it is. It&#8217;s remarkably easy to get the chart elements you want up and running with a few lines of Xaml, and you can mix and match them as you like. Some great examples are available in the Sample Explorer demo application included with the beta (as well as the full version, naturally) &#8211; check out the Composite Charts demo for some ideas.</p>
<p>The Sample Explorer also includes fully working and interactive examples of the two financial charts discussed in this post. Download it and check them out now, they&#8217;re <a href="http://www.mindscapehq.com/products/metroelements/download">available here</a>. The beta includes the financial charts along with 15 other great chart controls, and many other controls for data display and productivity. Thanks for reading; if you have any questions feel free to leave a comment or make a post in our <a href="http://www.mindscapehq.com/forums">forums</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/12/09/metro-elements-amazing-new-financial-charts-for-windows-store-apps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Win a Kindle Paperwhite, $50 Amazon gift card and license to Metro Elements worth $799 USD!</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/10/01/win-a-kindle-paperwhite-50-amazon-gift-card-and-license-to-metro-elements-worth-799-usd/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/10/01/win-a-kindle-paperwhite-50-amazon-gift-card-and-license-to-metro-elements-worth-799-usd/#comments</comments>
		<pubDate>Mon, 01 Oct 2012 22:51:58 +0000</pubDate>
		<dc:creator>hilary</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=5608</guid>
		<description><![CDATA[October 2012 is turning out to be a ripper of a month, what with new releases coming out left, right and center. Windows 8 is officially launched on the 25th, and the Kindle Paperwhite is due to come out on October 1st &#8211; not to mention the final version of Mindscape Metro Elements! So, in [...]]]></description>
				<content:encoded><![CDATA[<div id="attachment_5623" class="wp-caption alignright" style="width: 726px"><a href="http://www.mindscapehq.com/blog/index.php/2012/10/01/win-a-kindle-paperwhite-50-amazon-gift-card-and-license-to-metro-elements-worth-799-usd/mindscape-october-competition-2012/" rel="attachment wp-att-5623"><img class="size-full wp-image-5623" title="Mindscape-October-Competition-2012" src="http://www.mindscapehq.com/blog/wp-content/uploads/2012/09/Mindscape-October-Competition-2012.png" alt="" width="716" height="300" /></a><p class="wp-caption-text">A Kindle Paperwhite, $50 Amazon gift card and Metro Elements license are up for grabs this October</p></div>
<p>October 2012 is turning out to be a ripper of a month, what with new releases coming out left, right and center. Windows 8 is officially launched on the 25th, and the Kindle Paperwhite is due to come out on October 1st &#8211; not to mention the final version of Mindscape <a href="http://www.mindscapehq.com/products/metroelements">Metro Elements!</a></p>
<p>So, in honor of this exciting month, we&#8217;re making it even better by running a killer twitter competition. You can go in the draw to win:</p>
<ul>
<li>a <a href="http://www.amazon.com/Kindle-Paperwhite-Resolution-Display-Built-/dp/B007OZNZG0/ref=sr_tr_sr_1?s=digital-text&amp;ie=UTF8&amp;qid=1348701318&amp;sr=1-1&amp;keywords=paperwhite">Kindle Paperwhite</a>,</li>
<li>$50 worth of Amazon gift vouchers to spend on whatever you please (books for your brand new Kindle!?)</li>
<li>and a license to the <a href="http://www.mindscapehq.com/products/metroelements">Metro Elements</a> worth $799 USD!</li>
</ul>
<p>To enter this competition all you need to do is follow <a href="https://twitter.com/mindscapehq">@MindscapeHQ</a> on Twitter, and Tweet this blog post to your followers! You’ll see a little ‘tweet’ button beside this post so you can share it in less than a second. Easy!</p>
<p><a href="https://twitter.com/share" class="twitter-share-button" data-text="Win a Kindle Paperwhite, $50 Amazon gift card and license to Metro Elements worth $799 USD!" data-via="MindscapeHQ" data-count="none">Tweet</a><br />
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></p>
<p>Winner will be announced on the 31st October.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/10/01/win-a-kindle-paperwhite-50-amazon-gift-card-and-license-to-metro-elements-worth-799-usd/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Thanks To Our Biggest Fans!</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/06/25/thanks-to-our-biggest-fans/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/06/25/thanks-to-our-biggest-fans/#comments</comments>
		<pubDate>Mon, 25 Jun 2012 08:14:39 +0000</pubDate>
		<dc:creator>hilary</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=5128</guid>
		<description><![CDATA[The winners of the Annual CodeProject Awards were announced last week, with Mindscape winning recognition from members for providing what they consider to be awesome .NET tools. We&#8217;re super happy because this recognition means that our goal of building developer tools that make life easier for developers is being recognized. The awards are based on [...]]]></description>
				<content:encoded><![CDATA[<p>The winners of the Annual CodeProject Awards were announced last week, with Mindscape winning recognition from members for providing what they consider to be awesome .NET tools.</p>
<p>We&#8217;re super happy because this recognition means that our goal of building developer tools that make life easier for developers is being recognized. The awards are based on member votes, so we have you guys to thank for taking the time to vote. </p>
<p>A round of applause to you, our biggest fans. Thanks!</p>
<p><center><a href="http://www.mindscapehq.com/blog/index.php/2012/06/25/thanks-to-our-biggest-fans/winnerfinal2012hm/" rel="attachment wp-att-5132"><img class="size-full wp-image-5132" title="Members Choice Award Winner" src="http://www.mindscapehq.com/blog/wp-content/uploads/2012/06/winnerFinal2012HM.png" alt="" width="300" height="300" /></a></center></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/06/25/thanks-to-our-biggest-fans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nightly news, 1 June 2012</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/05/31/nightly-news-1-june-2012/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/05/31/nightly-news-1-june-2012/#comments</comments>
		<pubDate>Thu, 31 May 2012 22:39:27 +0000</pubDate>
		<dc:creator>Jeremy Boyd</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[LightSpeed]]></category>
		<category><![CDATA[Nightly news]]></category>
		<category><![CDATA[Web Workbench]]></category>
		<category><![CDATA[WPF Elements]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=5073</guid>
		<description><![CDATA[Lots of work this week in getting WPF Elements 5.1 shipped. Peering past all the grids, boxplots and candlestick charts here’s what you’ll find in this week’s nightly builds. WPF Elements WPF Elements 5.1 Released! Web Workbench Parse -browser functions in CSS Parse @selectors in CSS Fix for blue squiggly showing up on numeric selector [...]]]></description>
				<content:encoded><![CDATA[<p>Lots of work this week in getting <a href="http://www.mindscapehq.com/blog/index.php/2012/05/31/wpf-elements-5-1-released/" title="WPF Elements 5.1 Released">WPF Elements 5.1 shipped</a>. Peering past all the grids, boxplots and candlestick charts here’s what you’ll find in this week’s nightly builds.</p>
<p><a href="http://www.escapistmagazine.com/videos/view/zero-punctuation/5777-Diablo-3"><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2012/05/DeveloperNotes211.png" alt="" title="They are now regretting not using LightSpeed on the login servers" width="344" height="64" class="alignleft size-full wp-image-5007" /></a></p>
<p><strong>WPF Elements</strong></p>
<ul>
<li>WPF Elements 5.1 Released!</li>
</ul>
<p><strong>Web Workbench</strong></p>
<ul>
<li>Parse -browser functions in CSS</li>
<li>Parse @selectors in CSS</li>
<li>Fix for blue squiggly showing up on numeric selector names</li>
</ul>
<p><strong>LightSpeed</strong></p>
<ul>
<li>Added &#8220;Private Setter&#8221; property to entity properties in the designer, flows through to templating</li>
<li>Fixed an issue causing a SecurityException when running in medium trust</li>
</ul>
<p>As usual the <a href="http://www.mindscapehq.com/downloads/">free editions of the nightly builds are available right now from the downloads page</a>, and the <a href="http://www.mindscapehq.com/store/myaccount">full editions from the store</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/05/31/nightly-news-1-june-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mindscape video: Sh*t Developers DON&#8217;T Say</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/05/23/mindscape-video-sht-developers-dont-say/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/05/23/mindscape-video-sht-developers-dont-say/#comments</comments>
		<pubDate>Thu, 24 May 2012 04:39:18 +0000</pubDate>
		<dc:creator>hilary</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Video]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=5020</guid>
		<description><![CDATA[That&#8217;s right, the Mindscape staff have indeed ventured into the realm of acting and film making. But don&#8217;t worry, we haven&#8217;t quit our day jobs! Somebody has to keep up that legendary support that you all love right? Over the last few weeks though (in between working on new releases) we put together a bit [...]]]></description>
				<content:encoded><![CDATA[<p>That&#8217;s right, the Mindscape staff have indeed ventured into the realm of acting and film making. But don&#8217;t worry, we haven&#8217;t quit our day jobs! Somebody has to keep up that legendary support that you all love right?</p>
<p>Over the last few weeks though (in between working on new releases) we put together a bit of a film. Ok, so it&#8217;s more of a one minute clip, but the fame may have gone to our heads a little! It&#8217;s just a little bit of fun that we thought we could share.</p>
<p>And so we  proudly present, &#8220;Sh*t Developers DON&#8217;T Say&#8221; featuring real life Mindscape staff. In costume (true story).  We thought up some phrases that you will typically NEVER hear a developer say but if you think we&#8217;ve missed anything, go ahead and add it in the comments!</p>
<p>Enjoy, and we hope you&#8217;re as entertained as we were making it&#8230;</p>
<p><a href="http://www.youtube.com/watch?v=569aPUc0Sxo">http://www.youtube.com/watch?v=569aPUc0Sxo</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/05/23/mindscape-video-sht-developers-dont-say/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Go with the dataflow</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/04/18/go-with-the-dataflow/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/04/18/go-with-the-dataflow/#comments</comments>
		<pubDate>Wed, 18 Apr 2012 05:32:13 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=4925</guid>
		<description><![CDATA[Dataflow programming is a style that describes your data processing as data flowing through a graph of operations, in contrast to the usual imperative processing style. It invites you to think of data operations as a collection of black boxes, linked together by a runtime which takes care of moving data from one box to [...]]]></description>
				<content:encoded><![CDATA[<p>Dataflow programming is a style that describes your data processing as data flowing through a graph of operations, in contrast to the usual imperative processing style.  It invites you to think of data operations as a collection of black boxes, linked together by a runtime which takes care of moving data from one box to the next.</p>
<p>This may sound a little bit like LINQ, which makes it easy to compose set-based operations such as filtering and mapping without worrying about how the data gets from one operator to the next.  You might even be reminded of the PowerShell pipeline, which pipes objects between composable commandlets.  However, dataflow goes beyond a sequence of operations, allowing for flows to branch and join as required.  Dataflow is also typically asynchronous, allowing for data to arrive and begin processing at arbitrary times &#8212; in this it&#8217;s more like the Reactive Extensions than LINQ.</p>
<p>In .NET 4.5, you can do dataflow programming using the new System.Threading.Tasks.Dataflow DLL.  Here&#8217;s a quick look.</p>
<p><strong>Dataflow &#8216;Hello, world&#8217;</strong></p>
<p>If there&#8217;s one thing everybody hates more than a Fibonacci program, it&#8217;s a &#8216;Hello, world&#8217; program, right?  Well, tough.  Here it comes.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Set up the dataflow</span>
var helloifier <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransformBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;Hello, &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var printer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ActionBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>s<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
helloifier<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>printer<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Send some data into the dataflow</span>
helloifier<span style="color: #008000;">.</span><span style="color: #0000FF;">Post</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;world&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Prepare to be wowed&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>This program sets up an almost trivial dataflow, consisting of just two blocks, a <strong>transform block</strong> and an <strong>action block</strong>.  The transform block receives input, performs a transformation on it, and passes the result to its output.  It&#8217;s the dataflow equivalent of the LINQ Select operator.  In this case the transformation is to stick &#8220;Hello&#8221; on the front of the input.  The action block receives input, does something with it, and doesn&#8217;t produce any output.  In this case the thing it does is print it to the console.  The program links the output of the transform block to the input of the action block.</p>
<p>Next, the program posts some data into the dataflow &#8212; specifically into the transform block, since that&#8217;s where our flow begins.  Post is asynchronous, so it returns immediately, allowing the next statement to run.  (You can also use SendAsync, which returns a Task object you can await on to know when the block consumed your input &#8212; this can be handy if you&#8217;re throwing a lot of data at a block.)  Meanwhile the the dataflow kicks off in the background.  First the transform block runs, producing the output &#8220;Hello, world&#8221;; then this output is passed via the link to the action block, which dumps this to the console.  So the output is:</p>
<pre>
Prepare to be wowed
Hello, world
</pre>
<p>Notice that the Console.WriteLine in the main program ran before the one in the action block.</p>
<p><strong>Dataflow is parallel</strong></p>
<p>Obviously, dataflow isn&#8217;t terribly exciting for one message with trivial processing.  Things start to hot up though when you have multiple data items or heavier processing needs.  In this case dataflow will automatically parallelise the processing.  You can control this using the ExecutionDataflowBlockOptions.MaxDegreeOfParallelism setting.  In this example, I simulate CPU-bound operations in my transform and action blocks:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Busy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">1000000000</span><span style="color: #008000;">;</span> <span style="color: #008000;">++</span>i<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
var bustagut <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ExecutionDataflowBlockOptions <span style="color: #008000;">&#123;</span> MaxDegreeOfParallelism <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
var helloifier <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransformBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>
  s <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span> Busy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #666666;">&quot;Hello, &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>,
  bustagut<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var printer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ActionBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>
  s <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span> Busy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>s<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>,
  bustagut<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>When I pump a dozen or so messages into this on a quad-core machine, Task Manager shows me getting full value for money out of my CPU!</p>
<p><strong>Dataflow is push-friendly</strong></p>
<p>You&#8217;ll have noticed that I initiated the dataflow by calling Post (or SendAsync) to submit a data item into a block.  This is different from LINQ&#8217;s &#8220;pull&#8221; model.  In LINQ, data processing is initiated when I ask for a result.  This means dataflow is well suited to applications where data items are coming in unpredictably &#8212; for example, handling items coming in from a network or message queue &#8212; or even, heaven forbid, a user interface.</p>
<p>TPL dataflow integrates with Reactive Extensions and other observable APIs via the AsObserver and AsObservable extension methods.</p>
<p><strong>Dataflow is messaging</strong></p>
<p>So far this doesn&#8217;t seem to do anything more than LINQ (or, at any rate, Parallel LINQ&#8230; or at any rate, some sort of bizarre crossbreed of Parallel LINQ and Reactive Extensions&#8230; sorry, I&#8217;ll come in again).  Let&#8217;s build it up into more of a messaging system by adding in a <strong>broadcast block</strong>.  Broadcast takes an input and sends it to potentially multiple outputs.  So now we can take each data item and perform multiple operations on it in parallel &#8212; something not easily possible in LINQ.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var splitter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BroadcastBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> s<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var helloifier <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransformBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;Hello, &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var printer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ActionBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>s<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var businessifier <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransformBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;Dear &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var emailer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ActionBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> EmailToBoss<span style="color: #008000;">&#40;</span>s<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
splitter<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>helloifier<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
splitter<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>businessifier<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
helloifier<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>printer<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
businessifier<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>emailer<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Now each input is both printed to the console and emailed.  A simple use case for this might be a logging system where messages are stored locally in a CSV file and also uploaded to a Web service.</p>
<p>And once again, the two branches of the dataflow run in parallel.  Each block processes messages independently, so the various transformations and actions can all go at their own pace.</p>
<p><strong>Chunky versus chatty</strong></p>
<p>So far I&#8217;ve considered data items in isolation.  But when processing involves accessing a remote or expensive resource, processing each data item as it comes in may result in inefficient, chatty communication.  It may be more better to batch up a number of data items and submit them together.  No problem &#8212; just reach for the <strong>batch block</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var businessifier <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransformBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;Dear &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var batcher <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BatchBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var emailer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ActionBlock<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> EmailToBoss<span style="color: #008000;">&#40;</span>s<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// Action now takes array of string</span>
<span style="color: #008080; font-style: italic;">// ...</span>
businessifier<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>batcher<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
batcher<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>emailer<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Now the email method will be called only when there are five pending data items waiting to be processed, and all five will be passed to the email method in one go.</p>
<p>One complication with this is that a batch block doesn&#8217;t know when the stream of data has dried up and therefore won&#8217;t automatically flush an incomplete batch.  For this to work we need to do two things: first, we need to tell the dataflow network when we have no more input; and second, we need to propagate this through the network to the batch block.  To do the first, call the Complete() method on the input block; to do the second, specify a DataflowLinkOptions with PropagateCompletion = true on each link:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">businessifier<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>batcher, <span style="color: #008000;">new</span> DataflowLinkOptions <span style="color: #008000;">&#123;</span> PropagateCompletion <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
batcher<span style="color: #008000;">.</span><span style="color: #0000FF;">LinkTo</span><span style="color: #008000;">&#40;</span>emailer, <span style="color: #008000;">new</span> DataflowLinkOptions <span style="color: #008000;">&#123;</span> PropagateCompletion <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">13</span><span style="color: #008000;">;</span> <span style="color: #008000;">++</span>i<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  splitter<span style="color: #008000;">.</span><span style="color: #0000FF;">SendAsync</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;world &quot;</span> <span style="color: #008000;">+</span> i<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
splitter<span style="color: #008000;">.</span><span style="color: #0000FF;">Complete</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// no more data to come</span></pre></div></div>

<p>Another approach could be to have a watchdog that periodically calls BatchBlock.TriggerBatch &#8212; this would also ensure that batches are delivered in a timely way even if the rate of data items is very low.</p>
<p><strong>Add some dynamism to your dataflow</strong></p>
<p>An interesting feature of dataflow compared to LINQ is that dataflow blocks can be linked and unlinked at run time.  The LinkTo method returns an IDisposable which, when disposed, deletes the link.  This means you can dynamically update your processing flow at run time depending on resource availability, pricing, varying output requirements, etc.  You can even imagine giving users a simple diagramming tool for building their own analysis dataflows using transformation, aggregation and filtering blocks.</p>
<p><strong>Conclusion</strong></p>
<p>The examples of dataflow I&#8217;ve shown here are very trivial.  But hopefully you can see that it provides a flexible way of processing asynchronous messages, based on messaging principles rather than operating directly on sequences and scaling nicely to multiple cores.  TPL dataflow is part of .NET 4.5 so if you want to have a play with it just grab the Visual Studio 11 beta and give it a go!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/04/18/go-with-the-dataflow/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>What else is new in C# 5?</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/03/18/what-else-is-new-in-c-5/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/03/18/what-else-is-new-in-c-5/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 02:23:07 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=4727</guid>
		<description><![CDATA[The big new feature in C# 5 is asynchronous programming support, which I wrote about last week. However, the C# folks have also slipped in a couple of smaller features and I thought I&#8217;d round things out by mentioning those. Method caller information There&#8217;s a complete style guide to be written on Writing Enterprisey Code, [...]]]></description>
				<content:encoded><![CDATA[<p>The big new feature in C# 5 is <a href="http://www.mindscapehq.com/blog/index.php/2012/03/13/asynchronous-programming-in-c-5/">asynchronous programming support</a>, which I wrote about last week.  However, the C# folks have also slipped in a couple of smaller features and I thought I&#8217;d round things out by mentioning those.</p>
<p><strong>Method caller information</strong></p>
<p>There&#8217;s a complete style guide to be written on Writing Enterprisey Code, but one of my favourite &#8220;enterprisey&#8221; tells, after the use of Visual Basic, is obsessively logging every function you pass through:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #E56717; font-weight: bold;">Function</span> AddTwoNumbers(a <span style="color: #151B8D; font-weight: bold;">As</span> <span style="color: #F660AB; font-weight: bold;">Integer</span>, b <span style="color: #151B8D; font-weight: bold;">As</span> <span style="color: #F660AB; font-weight: bold;">Integer</span>) <span style="color: #151B8D; font-weight: bold;">As</span> <span style="color: #F660AB; font-weight: bold;">Integer</span>
  Logger.Trace(<span style="color: #800000;">&quot;ArithmeticHelpers&quot;</span>, <span style="color: #800000;">&quot;AddTwoNumbers&quot;</span>, <span style="color: #800000;">&quot;Entering AddTwoNumbers&quot;</span>)
  <span style="color: #151B8D; font-weight: bold;">Dim</span> result = OracleHelpers.ExecInteger(<span style="color: #800000;">&quot;SELECT &quot;</span> &amp; a &amp; <span style="color: #800000;">&quot; + &quot;</span> &amp; b)
  Logger.Trace(<span style="color: #800000;">&quot;ArithmeticHelpers&quot;</span>, <span style="color: #800000;">&quot;AddTwoNumbers&quot;</span>, <span style="color: #800000;">&quot;Calling PrintPurchaseOrders&quot;</span>)
  PrintPurchaseOrders()  <span style="color: #008000;">' IFT 12.11.96: don't know why this is needed but shipping module crashes if it is removed
</span>  Logger.Trace(<span style="color: #800000;">&quot;ArithmeticHelpers&quot;</span>, <span style="color: #800000;">&quot;AddTwoNumbers&quot;</span>, <span style="color: #800000;">&quot;Returned from PrintPurchaseOrders&quot;</span>)
  Logger.Trace(<span style="color: #800000;">&quot;ArithmeticHelpers&quot;</span>, <span style="color: #800000;">&quot;AddTwoNumbers&quot;</span>, <span style="color: #800000;">&quot;Exiting AddTwoNumbers&quot;</span>)
  Return result
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Function</span></pre></div></div>

<p>Although this code is efficient and clear by enterprisey standards, with C# 5 it can be even efficienter and clearer.  C# 4 introduced optional parameters, which meant callers of a method could leave out the arguments and the compiler would fill in the default values:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> WonderMethod<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> a <span style="color: #008000;">=</span> <span style="color: #FF0000;">123</span>, <span style="color: #6666cc; font-weight: bold;">string</span> b <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;hello&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">...</span> <span style="color: #008000;">&#125;</span>
&nbsp;
WonderMethod<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">456</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// compiles to WonderMethod(456, &quot;hello&quot;)</span>
WonderMethod<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>     <span style="color: #008080; font-style: italic;">// compiles to WonderMethod(123, &quot;hello&quot;)</span></pre></div></div>

<p>With C# 5, you can put a special attribute on an optional parameter and the compiler will fill in the value not with a constant but with information about the calling method.  This means we can implement the Logger.Trace to automagically pick up where it&#8217;s being called from:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Trace<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> message, <span style="color: #008000;">&#91;</span>CallerFilePath<span style="color: #008000;">&#93;</span> <span style="color: #6666cc; font-weight: bold;">string</span> sourceFile <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span>, <span style="color: #008000;">&#91;</span>CallerMemberName<span style="color: #008000;">&#93;</span> <span style="color: #6666cc; font-weight: bold;">string</span> memberName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #6666cc; font-weight: bold;">string</span> msg <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{0}: {1}.{2}: {3}&quot;</span>,
    DateTime<span style="color: #008000;">.</span><span style="color: #0000FF;">Now</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;yyyy-mm-dd HH:MM:ss.fff&quot;</span><span style="color: #008000;">&#41;</span>,  <span style="color: #008080; font-style: italic;">// Lurking 'minutes'/'months' bug introduced during .NET port in 2003 and has not been noticed because nobody ever looks at the log files because they contain too much useless detail</span>
    Path<span style="color: #008000;">.</span><span style="color: #0000FF;">GetFileNameWithoutExtension</span><span style="color: #008000;">&#40;</span>sourceFile<span style="color: #008000;">&#41;</span>,
    memberName,
    message<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  LoggingInfrastructure<span style="color: #008000;">.</span><span style="color: #0000FF;">Log</span><span style="color: #008000;">&#40;</span>msg<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Now, if the caller calls <code>Log.Trace("some message")</code> the compiler will fill in the missing arguments not with the empty string, but with the file and member where the call happens:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// In file Validation.cs</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> ValidateDatabase<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  Log<span style="color: #008000;">.</span><span style="color: #0000FF;">Trace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Entering method&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008080; font-style: italic;">// compiles to Log.Trace(&quot;Entering method&quot;, &quot;Validation.cs&quot;, &quot;ValidateDatabase&quot;)</span>
  Log<span style="color: #008000;">.</span><span style="color: #0000FF;">Trace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Exiting method&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Notice that the parameters to which you apply the attributes must be optional.  If they aren&#8217;t optional, the C# compiler will require the calling code to provide them, and the provided values will override the defaults.</p>
<p>Another example of how you can use this is in implementing INotifyPropertyChanged without needing either literal strings, expression magic or mystic weavers:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ViewModelBase <span style="color: #008000;">:</span> INotifyPropertyChanged <span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #6666cc; font-weight: bold;">void</span> Set<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> T field, T value, <span style="color: #008000;">&#91;</span>CallerMemberName<span style="color: #008000;">&#93;</span> <span style="color: #6666cc; font-weight: bold;">string</span> propertyName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">Object</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Equals</span><span style="color: #008000;">&#40;</span>field, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
      field <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
      OnPropertyChanged<span style="color: #008000;">&#40;</span>propertyName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
  <span style="color: #008080; font-style: italic;">// usual INPC boilerplate</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Widget <span style="color: #008000;">:</span> ViewModelBase <span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> _sprocketSize<span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> SprocketSize <span style="color: #008000;">&#123;</span>
    get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _sprocketSize<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    set <span style="color: #008000;">&#123;</span> Set<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> _sprocketSize, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>  <span style="color: #008080; font-style: italic;">// Compiler fills in &quot;SprocketSize&quot; as propertyName</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>For what it&#8217;s worth, you can also get the line number of the calling code using [CallerLineNumber].  This may be useful for diagnostic methods, but if you really need it, that may be a sign that the calling code is just a bit <em>too</em> enterprisey.</p>
<p><strong>Using loop variables in lambdas</strong></p>
<p>Technically, this is a fix to a long-standing cause of confusion and suffering.  But it makes C# that bit more usable, so I&#8217;m going to mention it anyway.</p>
<p>Since C# 3, it&#8217;s been quicker and easier to write anonymous functions than named ones, thanks to lambda syntax.  Anonymous functions are widely used in LINQ, but they&#8217;re also used in many other cases where you want to quickly parameterise behaviour without investing in some humungous hierarchy of classes and interfaces and virtual functions.  An important feature of anonymous functions is that they can capture variables from their local environment.  Here&#8217;s an example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> IEnumerable<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&gt;</span> GetGreaterThan<span style="color: #008000;">&#40;</span>IEnumerable<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&gt;</span> source, <span style="color: #6666cc; font-weight: bold;">int</span> n<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">return</span> source<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i <span style="color: #008000;">&gt;</span> n<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Here, <code>i => i > n</code> is an anonymous function that captures the value of n.  For example, if n is 17, then the function is <code>i => i > 17</code>.</p>
<p>In previous versions of C#, if you wrote a loop, you couldn&#8217;t use the loop variable in a lambda.  Actually, it was rather worse than that.  You could use the loop variable in a lambda, but it would give you the wrong results &#8212; it would use the value of the loop variable at the time the loop was exited, not at the time the variable was captured.</p>
<p>For example, here&#8217;s a function which returns a collection of &#8216;adder&#8217; functions, one &#8216;adder&#8217; for each addend in the input:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> List<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&gt;&gt;</span> GetAdders<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">params</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> addends<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  var funcs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> addend <span style="color: #0600FF; font-weight: bold;">in</span> addends<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    funcs<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i <span style="color: #008000;">+</span> addend<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
  <span style="color: #0600FF; font-weight: bold;">return</span> funcs<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Let&#8217;s take it for a spin:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var adders <span style="color: #008000;">=</span> GetAdders<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var adder <span style="color: #0600FF; font-weight: bold;">in</span> adders<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>adder<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Printout: 15 15 15 15 15</span></pre></div></div>

<p>Clearly this is horribly wrong!  Every function in the returned collection has ended up capturing 5 as its addend.  This is because they closed over the loop variable, addend, and the final value of the loop variable was 5.</p>
<p>To make this work in C# 3 and 4, you have to remember to copy the loop variable into a local variable (within the scope of the loop), and have your lambda close over the local variable:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var addend_ <span style="color: #0600FF; font-weight: bold;">in</span> addends<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  var addend <span style="color: #008000;">=</span> addend_<span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// DON'T GO NEAR THE LOOP VARIABLE</span>
  funcs<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i <span style="color: #008000;">+</span> addend<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Because the functions are closing over a local variable rather than the loop variable, the value is now preserved and you get the correct results.</p>
<p>This isn&#8217;t an obscure edge case by the way &#8212; I&#8217;ve come up against it numerous times in my projects.  A more realistic example from one project is building a function to perform filtering.  The function is built up from a collection of Restriction objects specified by the user.  The code loops over the Restriction objects and builds up a list of functions representing the clauses (e.g. Name Equals &#8220;BOB&#8221; becomes <code>r => r["Name"] == "BOB"</code>), then combines these functions into a final filter function which runs all of the clauses and checks they are all true.  My first pass at this didn&#8217;t work because each clause function ended up closing over the same Restriction object &#8212; the last one in the collection.</p>
<p>In C# 5, this is fixed and you can close over loop variables and get the results you expect.  If you like to take advantage of C#&#8217;s hybrid OO-functional nature, this removes a nasty bear trap that has been causing problems for years.</p>
<p>So that&#8217;s it for C# 5.  From a language point of view, there&#8217;s not a whole lot of new stuff to learn, though the async and await keywords conceal a great deal of depth.  Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/03/18/what-else-is-new-in-c-5/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>Asynchronous programming in C# 5</title>
		<link>http://www.mindscapehq.com/blog/index.php/2012/03/13/asynchronous-programming-in-c-5/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2012/03/13/asynchronous-programming-in-c-5/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 04:00:31 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=4693</guid>
		<description><![CDATA[One of the more radical design decisions in the forthcoming Windows Runtime is that no API may, even potentially, take more than 50 milliseconds to complete. Operations that could take longer than that will instead have a &#8216;kick off this operation&#8217; API that returns immediately without waiting for the result of the operation. The reason [...]]]></description>
				<content:encoded><![CDATA[<p>One of the more radical design decisions in the forthcoming Windows Runtime is that no API may, even potentially, take more than 50 milliseconds to complete.  Operations that could take longer than that will instead have a &#8216;kick off this operation&#8217; API that returns immediately without waiting for the result of the operation.  The reason for this is that Microsoft want Windows 8 Metro applications to be &#8216;fast and fluid&#8217; &#8212; with the immediacy of touch-based UIs, even small hiccups in responsiveness are more obvious and jarring than with a mouse or keyboard.  From a UI point of view, therefore, this is a very helpful design policy.</p>
<p>From a developer point of view, though, it makes life a bit tricky.  When we call read from a file or make a WCF service call, it&#8217;s usually because we want to do something with the result.  When the result is guaranteed to be available when the file read or WCF service API returns, we can write our code in a top-to-bottom form which is easy to understand and easy to reason about.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> url <span style="color: #008000;">=</span> ReadUrlFromFile<span style="color: #008000;">&#40;</span>filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> contentOfUrl <span style="color: #008000;">=</span> HttpGetFromUrl<span style="color: #008000;">&#40;</span>url<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>contentOfUrl<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>APIs like this are called synchronous or blocking.  Synchronous APIs are easy to use and understand, but your entire program (well, the current thread) is unresponsive while you&#8217;re inside one.  The API can&#8217;t return control to your code to do other tasks, because it can&#8217;t deliver the results yet.</p>
<p>The style of having a &#8216;kick off&#8217; API which returns immediately is called asynchronous or non-blocking.  Programming with asynchronous APIs is more difficult, because you can&#8217;t just return the results into a variable and keep going:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> url <span style="color: #008000;">=</span> BeginReadUrlFromFile<span style="color: #008000;">&#40;</span>filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// Won't work -- file read hasn't completed when BeginRead returns</span>
<span style="color: #6666cc; font-weight: bold;">string</span> contentOfUrl <span style="color: #008000;">=</span> BeginHttpGetFromUrl<span style="color: #008000;">&#40;</span>url<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// Ditto</span>
MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>contentOfUrl<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Instead, you have to put the code that uses the results into a callback, which the slow operation will invoke when it&#8217;s good and ready:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">BeginReadUrlFromFile<span style="color: #008000;">&#40;</span>filename, url <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span>
    BeginHttpGetFromUrl<span style="color: #008000;">&#40;</span>url, contentOfUrl <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span>
      MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>contentOfUrl<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Even a simplified example like this looks pretty ugly.  In real asynchronous code, with more operations being composed, more complex callbacks, conditional logic, early exits and error handling, well, it gets pretty ugly.  And the asynchronous APIs in the real .NET Framework are uglier still, with IAsyncResult objects and paired EndXxx method calls cluttering up the shop.</p>
<p>And yet this is the way our users would like us to work, and the way we will have to work if we want to target the Windows Runtime.</p>
<p><strong>The old solution: use F#</strong></p>
<p>The brainy folk behind F# figured out a way to get the best of both worlds.  F# includes a feature called <em>asynchronous workflows</em>, which are blocks of code introduced by <strong>async</strong>.  In an asynchronous workflow, you can call asynchronous methods using a syntax that looks just like synchronous code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">async <span style="color: #008000;">&#123;</span>
  let<span style="color: #008000;">!</span> url <span style="color: #008000;">=</span> BeginReadUrlFromFile filename
  let<span style="color: #008000;">!</span> contentOfUrl <span style="color: #008000;">=</span> BeginHttpGetFromUrl url
  MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>contentOfUrl<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The F# compiler automatically converts this nice readable, understandable code into the ghastly callback-style equivalent, thus giving you the ease of use of top-to-bottom coding with the responsive behaviour of asynchronous calls.</p>
<p><strong>The new solution: use C# 5</strong></p>
<p>Now, the equally brainy folk behind C# have implemented the same feature in C#.  The next version of C#, which is included in Visual Studio 11 beta, introduces two new keywords, <strong>async</strong> and <strong>await</strong>.</p>
<p>The async keyword simply indicates that a method makes asynchronous calls.  This is important for callers to know, because it means the method may return before it finishes &#8212; the method can yield back to its caller at any asynchronous call.</p>
<p>The await keyword indicates an asynchronous call where we want to keep writing top-to-bottom logic instead of writing out the callbacks by hand.  Here&#8217;s how they fit together:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> async <span style="color: #6666cc; font-weight: bold;">void</span> ShowReferencedContent<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> filename<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #6666cc; font-weight: bold;">string</span> url <span style="color: #008000;">=</span> await BeginReadFromFile<span style="color: #008000;">&#40;</span>filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #6666cc; font-weight: bold;">string</span> contentOfUrl <span style="color: #008000;">=</span> await BeginHttpGetFromUrl<span style="color: #008000;">&#40;</span>url<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>contentOfUrl<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This is much easier to write, read and sanity-check than the callback version, but it&#8217;s doing the same thing.  (Actually, it&#8217;s quite a bit smarter than the callback version, because compilers don&#8217;t get bored and skip over error conditions or screw up early exit logic or ignore threading issues.)</p>
<p>What happens when we call this method?  The first thing that happens is that BeginReadFromFile gets called, with the provided filename and the compiler-generated callback.  BeginReadFromFile returns immediately, but the result isn&#8217;t available yet.  So rather than assigning the result to the url variable &#8212; which is actually part of the callback &#8212; the method then exits and returns to the caller!  The calling method resumes and keeps running its code, even though the called method hasn&#8217;t yet finished.</p>
<p>Then, at some later point, the file system completes the read operation.  This means the result is now available, and the runtime schedules the callback.  This doesn&#8217;t necessarily happen immediately &#8212; the exact timing depends on the synchronisation context.  The callback runs, binds the url variable to the result of the file operation, and calls BeginHttpGetFromUrl.  This also returns immediately, meaning the method exits <em>again</em>.</p>
<p>Finally, the HTTP operation completes and the second callback runs.  This binds the contentOfUrl variable and, as in all bad demos, displays a message box with the result.</p>
<p><strong>What if I want to return a value to the caller?</strong></p>
<p>Async methods can exit before they&#8217;ve finished.  So if an async method wants to return a result, it has to recognise that it might return to the caller before that result is available.  For this reason, an async method that returns a value has to have a return type of <code>Task<T></code> rather than a &#8216;proper&#8217; value.  A Task represents a chunk of work which will eventually deliver a value, so a caller can examine the returned Task to determine when the result becomes available.  Here&#8217;s how an async method looks when returning a value:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> async Task<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span> GetReferencedContent<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> filename<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #6666cc; font-weight: bold;">string</span> url <span style="color: #008000;">=</span> await BeginReadFromFile<span style="color: #008000;">&#40;</span>filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #6666cc; font-weight: bold;">string</span> contentOfUrl <span style="color: #008000;">=</span> await BeginHttpGetFromUrl<span style="color: #008000;">&#40;</span>url<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">return</span> contentOfUrl<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Notice that the return statement takes a string, even though the return type is Task&lt;string&gt;.  Again, the compiler takes care of transforming the return statement to produce a Task.</p>
<p>Now a caller can call the GetReferencedContent method and either await on it to the string when it becomes available, or wait on it manually, or poll it for completion &#8212; whatever suits the way it intends to use the result.</p>
<p><strong>Async-friendly APIs</strong></p>
<p>If you&#8217;re familiar with asynchronous programming in .NET 4 and earlier, you&#8217;ll be used to paired Begin and End methods, such as WebRequest.BeginGetResponse and WebRequest.EndGetResponse.  These still exist in .NET 4.5, but they don&#8217;t work with the await keyword.  (Basically because a BeginXxx method requires an explicit method call inside the callback to get the result, and the compiler couldn&#8217;t depend on the EndXxx naming convention.)  Instead, .NET 4.5 provides new methods which return Task objects.  So instead of calling WebRequest.BeginGetResponse, you&#8217;ll call WebRequest.GetResponseAsync.  Here&#8217;s an example where we finally use some real .NET 4.5 async APIs:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> async Task<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span> GetContent<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> url<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  WebRequest wr <span style="color: #008000;">=</span> WebRequest<span style="color: #008000;">.</span><span style="color: #0000FF;">Create</span><span style="color: #008000;">&#40;</span>url<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  var response <span style="color: #008000;">=</span> await wr<span style="color: #008000;">.</span><span style="color: #0000FF;">GetResponseAsync</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var stm <span style="color: #008000;">=</span> response<span style="color: #008000;">.</span><span style="color: #0000FF;">GetResponseStream</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var reader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamReader<span style="color: #008000;">&#40;</span>stm<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      var content <span style="color: #008000;">=</span> await reader<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadToEndAsync</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">return</span> content<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Note how similar this looks to the synchronous code using WebRequest.GetResponse() and TextReader.ReadToEnd().  Just stick Async on the end of the API name and stuff an await in front of the call, and you&#8217;re good to go!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2012/03/13/asynchronous-programming-in-c-5/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: basic (Requested URI is rejected)
Database Caching 19/26 queries in 0.089 seconds using disk: basic

 Served from: www.mindscapehq.com @ 2013-05-26 02:59:06 by W3 Total Cache -->