<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>valerio.net</title>
	
	<link>http://thevalerios.net/matt</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Fri, 19 Jun 2009 22:39:30 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/ValerioDotNet" type="application/rss+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>F# Jobs on the Rise</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/SwWyrQyfNXs/</link>
		<comments>http://thevalerios.net/matt/2009/06/f-jobs-on-the-rise/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 15:12:10 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2009/06/f-jobs-on-the-rise/</guid>
		<description><![CDATA[I’ve received 3 inquiries in the last 2 weeks as to my “job availability status”, all surrounding my experience with F# on my resume. I’m no longer looking for a job (thankfully) and thought I had removed all references to my resume from my website, Dice, Monster, etc.&#160; I suppose there are still a few [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve received 3 inquiries in the last 2 weeks as to my “job availability status”, all surrounding my experience with F# on my resume. I’m no longer looking for a job (thankfully) and thought I had removed all references to my resume from my website, Dice, Monster, etc.&#160; I suppose there are still a few floating around somewhere.</p>
<p>I don’t know a lot of details about the positions these recruiters are trying to fill, but I did find out that one is in Columbus, OH and one is in Redmond, WA. In an effort to help out the F# community I figured I’d post about these jobs.&#160; There’s nothing in it for me.</p>
<p>If you are interested, shoot me an email and I’ll send you the contact information for the folks who called/emailed/talked to me.</p>
<p>Here’s my info:</p>
<p style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none" class="MsoNormal"><span style="font-family: &quot;Courier New&quot;; color: blue; font-size: 10pt; mso-no-proof: yes">let</span><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-no-proof: yes"> email =&#160; <br /></span><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>[(5,<span style="color: maroon">&quot;gmail&quot;</span>); (2,<span style="color: maroon">&quot;.&quot;</span>); (3,<span style="color: maroon">&quot;valerio&quot;</span>); (6,<span style="color: maroon">&quot;.&quot;</span>); (1,<span style="color: maroon">&quot;matt&quot;</span>);      <br />&#160;&#160;&#160;&#160; (7,<span style="color: maroon">&quot;com&quot;</span>); (4,<span style="color: maroon">&quot;@&quot;</span>)]      <br /></span><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>|&gt; List.sortBy fst      <br /></span><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>|&gt; List.map snd      <br /></span><span style="line-height: 115%; font-family: &quot;Courier New&quot;; font-size: 10pt; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>|&gt; List.reduce (^)</span></p>
<p> <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/SwWyrQyfNXs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2009/06/f-jobs-on-the-rise/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2009/06/f-jobs-on-the-rise/</feedburner:origLink></item>
		<item>
		<title>Hunting the Elusive ‘tail’ Opcode in F#</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/gu8SMTnSTwQ/</link>
		<comments>http://thevalerios.net/matt/2009/06/hunting-the-elusive-tail-opcode-in-f/#comments</comments>
		<pubDate>Thu, 18 Jun 2009 05:00:53 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tail recursion]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2009/06/hunting-the-elusive-tail-opcode-in-f/</guid>
		<description><![CDATA[Awhile back I wrote a post about tail-call optimizations that the F# compiler used to eliminate stack overflows. Brian McNamera commented about another optimization that I didn’t illustrate – the ‘tail’ opcode that appears when mutually-recursive and indirectly-recursive functions are encountered. Tail-call optimization is one of the really powerful features of F#, so I really [...]]]></description>
			<content:encoded><![CDATA[<p>Awhile back I <a href="http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/">wrote a post</a> about tail-call optimizations that the F# compiler used to eliminate stack overflows. Brian McNamera commented about another optimization that I didn’t illustrate – the ‘tail’ opcode that appears when mutually-recursive and indirectly-recursive functions are encountered. Tail-call optimization is one of the really powerful features of F#, so I really wanted to see how this worked under the hood.</p>
<p>The first thing we need is a pair of mutually-recursive functions.  The easiest (laziest? <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) way to do this is to write one function (e.g. f1) and duplicate its implementation as another name (e.g. f2):</p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; color: green; font-size: 9.5pt;">// Hunting for tail calls</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; color: green; font-size: 9.5pt;">// 6.17.09</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; color: blue; font-size: 9.5pt;">open</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> System </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; color: blue; font-size: 9.5pt;">let</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> <span style="color: blue;">rec</span> sum1 n acc = </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span><span style="color: blue;">match</span> n <span style="color: blue;">with</span> </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span>| 0 <span style="color: blue;">-&gt;</span> acc </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span>| _ <span style="color: blue;">-&gt;</span> sum2 (n-1) (acc+n) </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; color: blue; font-size: 9.5pt;">and</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> sum2 n acc = </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span><span style="color: blue;">match</span> n <span style="color: blue;">with</span> </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span>| 0 <span style="color: blue;">-&gt;</span> acc </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span>| _ <span style="color: blue;">-&gt;</span> sum1 (n-1) (acc+n) </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span></span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; color: blue; font-size: 9.5pt;">let</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> sum n = sum1 n 0 </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; color: blue; font-size: 9.5pt;">let</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"> main () = </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">   </span>Console.WriteLine(<span style="color: maroon;">&#8220;Hello&#8221;</span>) </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">   </span>printfn <span style="color: maroon;">&#8220;%A&#8221;</span> (sum 100000) </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">   </span>Console.WriteLine(<span style="color: maroon;">&#8220;Press Enter to continue&#8230;&#8221;</span>) </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">   </span>Console.ReadLine() |&gt; ignore </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-spacerun: yes">    </span></span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;">main () </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">After compiling this, I popped open the resulting executable in Reflector. Of course I wasn’t going to find the ‘tail’ opcode by looking at the C# – I needed to disassemble the IL. I hunted and hunted for the ‘tail’ opcode, but couldn’t find it!  Every call to f1 from f2 (and f2 from f1) used the stack to pass around n and acc. Even stranger – this is the first F# program I’d written using Visual Studio 2010, and I could have sworn that I’d done the same thing with F# in Visual Studio 2008 a couple months ago.</p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">After building the project again, I noticed the command-line arguments passed to fsc:</p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;">&#8212;&#8212; Build started: Project: HuntingTailcalls, Configuration: Debug Any CPU &#8212;&#8212; </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><span style="font-family: consolas; font-size: 9.5pt;"><span style="mso-tab-count: 2">              </span>C:\Program Files\Microsoft F#\v4.0\fsc.exe -o:obj\Debug\HuntingTailcalls.exe -g &#8211;debug:full &#8211;noframework &#8211;define:DEBUG &#8211;define:TRACE &#8211;optimize- <span style="background: yellow; mso-highlight: yellow">&#8211;tailcalls-</span> -r:&#8221;C:\Program Files\Microsoft F#\v4.0\FSharp.Core.dll&#8221; -r:&#8221;C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll&#8221; -r:&#8221;C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll&#8221; -r:&#8221;C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll&#8221; &#8211;target:exe &#8211;warn:3 &#8211;warnaserror:76 &#8211;vserrors &#8211;utf8output &#8211;fullpaths &#8211;flaterrors Program.fs </span></div>
<p><span style="font-family: consolas; font-size: 9.5pt;"> </p>
<p></span></p>
<p class="MsoNormal">“—tailcalls-“? Somehow tailcalls are being turned off. Maybe there’s something in the project settings that are disabling the tailcalls? Ah-ha! The checkbox was unchecked <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p class="MsoNormal"><a href="http://thevalerios.net/matt/wp-content/uploads/2009/06/image.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/06/image-thumb.png" border="0" alt="image" width="644" height="369" /></a></p>
<p class="MsoNormal">After poking around a bit more, I discovered that by default the “Generate tail calls” box is unchecked fo Debug mode, and checked by default for Release mode.  Hmmm, interesting.</p>
<p class="MsoNormal">After switching to Release mode, I rebuild the project and opened the .exe in Reflector.  Here we go! There’s the elusive ‘tail’ opcode:</p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; color: #1000a0; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;">.method</span></p>
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> <span style="color: #1000a0;">public</span> <span style="color: #1000a0;">static</span> <a title="int32" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:4.0.0.0:b77a5c561934e089/System.Int32"><span style="color: blue;">int32</span></a> <strong><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://HuntingTailcalls/Program/sum1(Int32,Int32):Int32"><span style="color: blue;">sum1</span></a></strong>(<a title="int32" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:4.0.0.0:b77a5c561934e089/System.Int32"><span style="color: blue;">int32</span></a> n, <a title="int32" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:4.0.0.0:b77a5c561934e089/System.Int32"><span style="color: blue;">int32</span></a> acc)<span style="color: #1000a0;"> cil managed</span> </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;">{ </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span><span style="color: #1000a0;">.maxstack</span> 5 </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_0000: ldarg.0 </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_0001: switch (L_0019) </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_000a: nop </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_000b: ldarg.0 </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_000c: ldc.i4.1 </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_000d: sub </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_000e: ldarg.1 </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_000f: ldarg.0 </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_0010: add </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_0011: <span style="background: yellow; mso-highlight: yellow">tail</span> </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_0013: call <a title="int32" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:4.0.0.0:b77a5c561934e089/System.Int32"><span style="color: blue;">int32</span></a> <a title="Program" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://HuntingTailcalls/Program"><span style="color: blue;">Program</span></a>::<a title="sum2" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://HuntingTailcalls/Program/sum2(Int32,Int32):Int32"><span style="color: blue;">sum2</span></a>(<a title="int32" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:4.0.0.0:b77a5c561934e089/System.Int32"><span style="color: blue;">int32</span></a>, <a title="int32" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:4.0.0.0:b77a5c561934e089/System.Int32"><span style="color: blue;">int32</span></a>) </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_0018: ret </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_0019: ldarg.1 </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt">
<div class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt"><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"><span style="mso-spacerun: yes">    </span>L_001a: ret </span></div>
<p><span style="font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;;"> </p>
<p></span><span style="line-height: 115%; font-family: &quot;Courier New&quot;; font-size: 10pt; mso-fareast-font-family: &quot;Times New Roman&quot;; mso-ansi-language: en-us; mso-fareast-language: en-us; mso-bidi-language: ar-sa;">}</span></p>
<p class="MsoNormal">(The IL code for sum2 looks identical.) Interestingly enough, the C# code from Reflector looks exactly the same between Debug and Release modes (with and without tail calls) – C# doesn’t have the capability to make tail calls.</p>
<p class="MsoNormal">Well, there you have it! We finally found the elusive ‘tail’ opcode.</p>
<p class="MsoNormal">That being said, be sure to keep this in mind – the default settings of Visual Studio 2010 for F# development are drastically different between Debug and Release mode.  Bugs might crop up in Debug mode (e.g. StackOverflowExceptions) that don’t rear their heads in Release mode.</p>
<p class="MsoNormal">I think the motivation for this is that using tail calls severely limit the usefulness of the Visual Studio debugger since it relies on traversing the stack frame (that the tail opcode destroys) to display debugging information.</p>
<p class="MsoNormal">For example, without tailcall optimizations setting a breakpoint on sum1 looks like this:</p>
<p class="MsoNormal"><a href="http://thevalerios.net/matt/wp-content/uploads/2009/06/image1.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/06/image-thumb1.png" border="0" alt="image" width="244" height="145" /></a></p>
<p class="MsoNormal"><a href="http://thevalerios.net/matt/wp-content/uploads/2009/06/image2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/06/image-thumb2.png" border="0" alt="image" width="628" height="297" /></a></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">The callstack shows some useful debugging information, specifically the values of n and the accumulator.</p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">However, if we enable tailcall optimization, this breaks down after running through the breakpoint 10 times, each time it shows one line with different information:</p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><a href="http://thevalerios.net/matt/wp-content/uploads/2009/06/image3.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/06/image-thumb3.png" border="0" alt="image" width="496" height="107" /></a></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none"><a href="http://thevalerios.net/matt/wp-content/uploads/2009/06/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/06/image-thumb4.png" border="0" alt="image" width="496" height="107" /></a></p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">… You get the idea.</p>
<p class="MsoNormal" style="line-height: normal; margin-bottom: 0pt; mso-layout-grid-align: none">Hope that sheds some light on tailcall optimization, as well as some of the new features of F# in Visual Studio 2010!</p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/gu8SMTnSTwQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2009/06/hunting-the-elusive-tail-opcode-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2009/06/hunting-the-elusive-tail-opcode-in-f/</feedburner:origLink></item>
		<item>
		<title>Hosting Subversion In the Cloud with Live Mesh</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/603fdiE5B1k/</link>
		<comments>http://thevalerios.net/matt/2009/02/hosting-subversion-in-the-cloud-with-live-mesh/#comments</comments>
		<pubDate>Sun, 22 Feb 2009 05:43:55 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[live]]></category>
		<category><![CDATA[mesh]]></category>
		<category><![CDATA[subversion]]></category>
		<category><![CDATA[tortoisesvn]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2009/02/hosting-subversion-in-the-cloud-with-live-mesh/</guid>
		<description><![CDATA[This afternoon I was going back through some of the code I&#8217;d written for various blog posts that I&#8217;d kept in a Subversion repository.&#160; During the move things have been in limbo and I haven&#8217;t had time to set up the SVN server again. I thought &#8220;Hmm, I wonder if I could host my Subversion [...]]]></description>
			<content:encoded><![CDATA[<p>This afternoon I was going back through some of the code I&#8217;d written for various blog posts that I&#8217;d kept in a <a href="http://subversion.tigris.org/">Subversion</a> repository.&nbsp; During the move things have been in limbo and I haven&#8217;t had time to set up the SVN server again. I thought &#8220;Hmm, I wonder if I could host my Subversion repository in the cloud&#8221;.</p>
<p>Enter <a href="https://www.mesh.com/">Live Mesh</a>. It lets you add multiple devices to your mesh network and automatically synchronize your files between devices.&nbsp; Pretty cool stuff.</p>
<p>At first I thought it would be a great place to put all of my source code &#8212; then I could have the code on every computer.&nbsp; However, what if you have working code on your desktop, then open up the code on your laptop and introduce a few bugs.&nbsp; When you go to open up the project on the desktop again, those bugs are there automatically.&nbsp; The synchronization is great, but there&#8217;s no way to keep version information in case you want to revert to a previous snapshot of the files.</p>
<p>Anyone familiar with Subversion will remember that there are two main parts to an installation &#8212; the Subversion repository (could be local or remote) and another folder with the checked-out files. A not-uncommon setup for personal development work is to have a local Subversion repository as a directory on the local file system.&nbsp; I wonder what would happen if I used slapped a local repository installation into a Live Mesh folder? Well, it would get automatically synchronized between machines. All devices in the network would have an SVN client installed (e.g. <a href="http://tortoisesvn.tigris.org/">TortoiseSVN</a>) and pointed to the Mesh-synchronized folder.&nbsp; I think this just might work <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>For anyone interested, here are the steps that I followed to set this up.</p>
<p>Open up your Live Mesh Folders from My Computer:<a href="http://thevalerios.net/matt/wp-content/uploads/2009/02/image.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="354" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/02/image-thumb.png" width="423" border="0"></a> </p>
<p>Set up a new folder named &#8220;Subversion&#8221;. Make sure that all of the devices in your Live Mesh network are set to &#8220;When files are added or modified&#8221; in the synchronization options.<a href="http://thevalerios.net/matt/wp-content/uploads/2009/02/image2.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="446" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/02/image-thumb2.png" width="487" border="0"></a>  </p>
<p>Browse over to the location (Subversion folder on my desktop), open it up, and create another folder inside called &#8220;Repository&#8221;.</p>
<p>Then, right-click on the Repository folder -&gt; TortoiseSVN -&gt; Create repository here. It&#8217;s important to note here that the extra &#8220;Repository&#8221; directory is important since you can&#8217;t directly create the repository in the &#8220;Subversion&#8221; folder one level up.&nbsp; There is some interaction between TortoiseSVN and Live Mesh that keeps it from working.</p>
<p>Then, go back to the desktop (or any other place) and make a folder called &#8220;Checkout&#8221;.&nbsp; Right-click on the Checkout folder and select &#8220;SVN Checkout&#8230;&#8221;</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2009/02/image1.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="350" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/02/image-thumb1.png" width="456" border="0"></a> </p>
<p>Make sure that the &#8220;URL of repository&#8221; field is pointed towards the &#8220;Subversion/Repository&#8221; directory and the &#8220;Checkout directory&#8221; field is pointed towards the &#8220;Checkout\Repository&#8221; directory and click OK.</p>
<p>There you go &#8212; use the checked-out subversion repository as you wish and just point your SVN client on each device to the Mesh-synchronized folder.</p>
<p>Hope someone finds this useful! <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>UPDATE:</strong> Looks like <a href="http://www.zimmergren.net/archive/2009/02/05/backing-up-your-local-subversion-repositories-using-live-mesh.aspx">I&#8217;m not the first to think of doing this</a> <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/603fdiE5B1k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2009/02/hosting-subversion-in-the-cloud-with-live-mesh/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2009/02/hosting-subversion-in-the-cloud-with-live-mesh/</feedburner:origLink></item>
		<item>
		<title>Big Changes</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/wcF3tECzzG4/</link>
		<comments>http://thevalerios.net/matt/2009/02/big-changes/#comments</comments>
		<pubDate>Thu, 05 Feb 2009 06:08:49 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2009/02/big-changes/</guid>
		<description><![CDATA[The blog&#8217;s been pretty quiet lately for good reason &#8212; I simply haven&#8217;t had a spare second to post anything. I have quite a few interesting posts in the wings just waiting for a last bit of polishing.
Why so busy?&#160; Well, since the end of November I applied for, interviewed for, was offered, and accepted [...]]]></description>
			<content:encoded><![CDATA[<p>The blog&#8217;s been pretty quiet lately for good reason &#8212; I simply haven&#8217;t had a spare second to post anything. I have quite a few interesting posts in the wings just waiting for a last bit of polishing.</p>
<p>Why so busy?&nbsp; Well, since the end of November I applied for, interviewed for, was offered, and accepted a job at Microsoft <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> &nbsp; As a consequence, I&#8217;ve been extremely busy getting ready for and making the cross-country move from Columbus, OH to Redmond, WA.&nbsp; Needless to say, it was a very exciting and nerve-wracking last few weeks.</p>
<p>I started as a SDE (software development engineer) in the <a href="http://www.microsoft.com/hsg/">Health Solutions Group</a> last Monday. I&#8217;m still learning the ropes and certainly relate to the feeling of &#8220;<a href="http://haacked.com/archive/2007/10/26/drinking-from-the-firehose.aspx">drinking from the fire hose</a>&#8220;. Today was a &#8220;momentous&#8221; occasion as I submitted my first bugfix, only to quickly discover the need to submit a bugfix for my bugfix. It&#8217;s quite humbling being completely surrounded by veritable developer rockstars.</p>
<p>Despite all of the stress, I am absolutely and totally pumped to be here &#8212; my project is awesome and the people I work with are awesome &#8212; there are very exciting times ahead <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Hopefully as things start to settle down I&#8217;ll get some time to braindump about all of the cool things going on. <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/wcF3tECzzG4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2009/02/big-changes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2009/02/big-changes/</feedburner:origLink></item>
		<item>
		<title>Recursion in F# and the Tail Recursion Police</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/LsEfiDLMjgw/</link>
		<comments>http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 16:53:32 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[Reflector]]></category>
		<category><![CDATA[tail recursion]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/</guid>
		<description><![CDATA[A helpful comment on a post over at HubFS by Brian McNamara really helped me wrap my mind around tail recursion and why it&#8217;s immensely important to understand in F#. Brian coined the phrase &#8220;tail recursion police&#8221;, hence the title  
Recursion pops up quite a bit in functional programming so it&#8217;s a good idea [...]]]></description>
			<content:encoded><![CDATA[<p>A helpful comment on a <a href="http://cs.hubfs.net/forums/thread/8022.aspx">post</a> over at <a href="http://cs.hubfs.net/forums/default.aspx">HubFS</a> by <a href="http://lorgonblog.spaces.live.com/blog/">Brian McNamara</a> really helped me wrap my mind around tail recursion and why it&#8217;s immensely important to understand in F#. Brian coined the phrase &#8220;tail recursion police&#8221;, hence the title <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Recursion pops up quite a bit in functional programming so it&#8217;s a good idea to understand the risks/tradeoffs/benefits. A gross simplification of an analogy would be:</p>
<blockquote><p>For loops : C# :: Recursion : F#</p>
</blockquote>
<p>Sure, you can do for-loops and imperative-style coding in F#, but it doesn&#8217;t showcase the beauty of the functional style programming that F# offers.</p>
<p>Recursive functions (in both C# and F#) are just functions that call themselves.&nbsp; They do so by pushing the current state of the function onto the stack, popping them off when calls start completing. Because the stack is a limited resource, it can be exhausted (StackOverflowException) if the function is called recursively too many times.&nbsp; </p>
<p>These kinds of runtime exceptions can be difficult to find unless explicitly tested for, leading to hard-to-find bugs.&nbsp; Oftentimes tests will only exercise simple cases of algorithms and then fail at runtime when large (real-world) inputs are used. After all, &#8220;everything works for small N&#8221;.</p>
<p>F#, however, has a very interesting feature where (under certain conditions), it can recognize recursive functions and perform a &#8220;tail call optimization&#8221;, turning the recursive function into a while-loop that uses <em>no stack space whatsoever</em>. This is called tail recursion.</p>
<p>The rule for tail-recursion is simple:</p>
<blockquote><p>If the recursive call to the function is the very last thing that happens in the algorithm, then the function can be made tail-recursive.</p>
</blockquote>
<p>In most cases a recursive algorithm can be expressed in both recursive and tail-recursive forms. Other times, it may not even be possible to implement a specific algorithm tail-recursively. </p>
<p>Let&#8217;s look at some examples.</p>
<h4>Tail Recursive or Not?</h4>
<p>One way to implement the &#8220;map&#8221; function that applies a specific function, f, to every element in a list would be:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">let</span> <span style="color: blue">rec</span> map f l =</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">match</span> l <span style="color: blue">with</span></p>
<p style="margin: 0px">&nbsp; | [] <span style="color: blue">-&gt;</span> []</p>
<p style="margin: 0px">&nbsp; | h::t <span style="color: blue">-&gt;</span> f h :: map f t</p>
</div>
<p>While this implementation easily expresses the algorithm (splitting a list into its head and tail, applying the function f to the head, and consing it to the list obtained from applying the function to the tail), it is NOT tail recursive! The recursive call to &#8220;map&#8221; must happen, then f is applied to h, and then the results are cons&#8217;d (:: operator).&nbsp; The recursive call to &#8220;map&#8221; is not last in this instance, so it&#8217;s not tail-recursive.</p>
<p>How can we make this map operation tail-recursive? Typically this involves 2 things &#8212; factoring out an inner loop that is recursive and threading an accumulator through that inner loop:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">let</span> mapTR f l =</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> <span style="color: blue">rec</span> loop f2 l2 acc =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">match</span> l2 <span style="color: blue">with</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; | [] <span style="color: blue">-&gt;</span> acc</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; | h::t <span style="color: blue">-&gt;</span> loop f2 t ((f2 h)::acc)</p>
<p style="margin: 0px">&nbsp; loop f l [] |&gt; List.rev</p>
</div>
<p>In the 2nd-to-last line, f2 is applied to the head, then cons&#8217;d with the accumulator, and that result (along with f2 and the tail) are passed to the recursive call to &#8220;loop&#8221;.&nbsp; In this case, &#8220;loop&#8221; is the very last thing that happens, so the F# compiler can implement this tail-recursively.</p>
<h4>Double-Check with Reflector</h4>
<p>We can double-check that the F# compiler created a recursive function for the &#8220;map&#8221; case by using Reflector.&nbsp; While F#-compiled-to-IL-decompiled-to-C# can be a bit verbose thanks to all of the generics and partial function application (FastFunc), it can still be seen that the map function recursively calls itself.</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2009/01/image3.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="166" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/01/image-thumb3.png" width="339" border="0"></a> </p>
<p>If the Tail Recursion Police were out, we&#8217;d be totally busted.</p>
<p>For the &#8220;mapTR&#8221; case, the implementation is a bit hidden behind some closures, but can be found with a little work.&nbsp; The meat of the tail-recursive function is implemented with a while(true) loop! This is fantastic since it uses no stack space. The Tail Recursion Police would let us off clean on this one.</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2009/01/image4.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="226" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/01/image-thumb4.png" width="276" border="0"></a> </p>
<p>Sidenote: The List&lt;T&gt; type here is not the standard System.Collections.Generic.List&lt;T&gt;.&nbsp; It is a singly-linked list that is part of the F# core libraries. In F# the Generic.List&lt;T&gt; is known as ResizeArray&lt;T&gt; since it more resembles a resizable array than a singly-linked list.</p>
<p>Sidenote 2: I&#8217;ve heard some things about the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.tailcall(VS.95).aspx">&#8220;.tail&#8221; IL opcode</a>, but don&#8217;t see it popping up anywhere in this code. The while loop seems more efficient to me than a recursive call that drops the current stack frame, though. I&#8217;m not entirely sure what the relationship is between the .tail opcode is and tail recursion in F#.</p>
<p>Let&#8217;s walk through another example and dig into a little more detail.</p>
<h4>Kaboom! StackOverflowException Strikes</h4>
<p>When working on some code over the weekend, I ran into the need for a slightly different version of List.map. The &#8220;map&#8221; function has the signature &#8220;(&#8217;a -&gt; &#8216;b) -&gt; &#8216;a list -&gt; &#8216;b list&#8221; &#8212; that is, it takes a function that takes a &#8216;a and returns a &#8216;b as well as a &#8216;a list to operate on, producing a &#8216;b list. It simply applies the given function to each item in the list and returns a new list with the result of each function application.</p>
<p>What I needed, however, was a method that took a list of one type and returned a list of another type, but applied a function that accepted a list of values and produces a resulting value.&nbsp; That is, I needed a function with a signature &#8220;(&#8217;a list -&gt; &#8216;b) -&gt; &#8216;a list -&gt; &#8216;b list&#8221;. When you think about this, I needed an algorithm that would operate on the initial list by calling a method by &#8220;snapping off&#8221; successive portions of the list, producing another list.&nbsp; So, if we had a list [1;2;3;4], the mapping function would be called in succession with input lists [1;2;3;4], [2;3;4], [3;4], [4], and []. Since it&#8217;s still doing a mapping, though making the entire list (instead of just the head of the list) available to the mapping function, I decided to call it &#8220;mapl&#8221; for &#8220;map list&#8221;.</p>
<p>My first stab at an implementation was straightforward:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">module</span> List =</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> <span style="color: blue">rec</span> mapl f l =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">match</span> l <span style="color: blue">with</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; | [] <span style="color: blue">-&gt;</span> []</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; | h::t <span style="color: blue">-&gt;</span> f l :: mapl f t </p>
</div>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&gt; <span style="color: blue">let</span> test = [1;2;3;4];;</p>
<p style="margin: 0px"><span style="color: blue">val</span> test : int list</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&gt; test |&gt; List.mapl (printfn <span style="color: maroon">&#8220;%A&#8221;</span>);;</p>
<p style="margin: 0px">[1; 2; 3; 4]</p>
<p style="margin: 0px">[2; 3; 4]</p>
<p style="margin: 0px">[3; 4]</p>
<p style="margin: 0px">[4]</p>
</div>
<p>Good so far. However, it&#8217;s not tail-recursive, so let&#8217;s see if we can break it:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">&gt; [1..100000] |&gt; List.mapl List.hd;;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">Process is terminated due <span style="color: blue">to</span> StackOverflowException.</p>
<p style="margin: 0px">Session termination detected. Press Enter <span style="color: blue">to</span> restart.</p>
</div>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2009/01/image5.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="262" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/01/image-thumb5.png" width="501" border="0"></a> </p>
<p>Kaboom! The Tail Recursion Police are already on the scene, cleaning up the remains of fsi.exe&#8230; </p>
<h4>Tail-Recursion Tweaks and Performance</h4>
<p>Ok, so let&#8217;s make this &#8220;mapl&#8221; function tail-recursive. I wanted to investigate 3 different approaches and compare the performance based on slight nuances between the implementations.</p>
<p>Here&#8217;s my code for mapl_tr1, mapl_tr2, and mapl_tr3:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">module</span> List =</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> mapl_tr1 f l =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">let</span> <span style="color: blue">rec</span> loop l2 acc =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">match</span> l2 <span style="color: blue">with</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | [] <span style="color: blue">-&gt;</span> acc</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | h::t <span style="color: blue">-&gt;</span> loop t ((f l2)::acc)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; loop l []</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> mapl_tr2 f l =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">let</span> <span style="color: blue">rec</span> loop f2 l2 acc =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">match</span> l2 <span style="color: blue">with</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | [] <span style="color: blue">-&gt;</span> acc</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | h::t <span style="color: blue">-&gt;</span> loop f2 t ((f2 l2)::acc)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; loop f l []</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> mapl_tr3 f l =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">let</span> <span style="color: blue">rec</span> loop (f2, l2, acc) =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">match</span> l2 <span style="color: blue">with</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | [] <span style="color: blue">-&gt;</span> acc</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | h::t <span style="color: blue">-&gt;</span> loop (f2, t, ((f2 l2)::acc))</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; loop (f, l, [])</p>
</div>
<p>You can see that we factored out an inner loop that is recursive, added an accumulator list, and made sure that the loop function call was the last operation before recursing.</p>
<ul>
<li>mapl_tr1: This function captures the function &#8220;f&#8221; (a closure) from within the inner loop.</li>
<li>mapl_tr2: This function explicitly passes the function &#8220;f&#8221; to the inner loop to test if a closure slows things down</li>
<li>mapl_tr3: This function creates tuples when passing values to the inner loop and recursing to test if tuples are faster than partial function applications</li>
</ul>
<p>To test these functions out, I used a simple test harness:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">let</span> main () =</p>
<p style="margin: 0px">&nbsp; printfn <span style="color: maroon">&#8220;Tail Recursion Test&#8221;</span></p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> run_test m =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; time_iter 10 (<span style="color: blue">fun</span> () <span style="color: blue">-&gt;</span> [1 .. 100000] |&gt; m List.hd |&gt; ignore)</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> methods = [List.mapl_tr1; List.mapl_tr2; List.mapl_tr3]</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> names = [<span style="color: maroon">"mapl_tr1"</span>; <span style="color: maroon">"mapl_tr2"</span>; <span style="color: maroon">"mapl_tr3"</span>]</p>
<p style="margin: 0px">&nbsp; methods</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; List.map run_test</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; List.zip names</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; List.iter (<span style="color: blue">fun</span> i <span style="color: blue">-&gt;</span> printfn <span style="color: maroon">&#8220;%s: %f ms&#8221;</span> (fst i) (snd i))</p>
<p style="margin: 0px">&nbsp; press_enter ()</p>
</div>
<p>This takes a list of the three methods (isn&#8217;t it great to pass around code as data in functional languages?), run a test by timing it and taking the average of 10 executions, then print out the results.</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">Tail Recursion Test</p>
<p style="margin: 0px">mapl_tr1: 46.616836 ms</p>
<p style="margin: 0px">mapl_tr2: 42.788645 ms</p>
<p style="margin: 0px">mapl_tr3: 65.175500 ms</p>
<p style="margin: 0px">Press Enter to continue&#8230;</p>
</div>
<p>Wow, that&#8217;s really interesting. mapl_tr1 and mapl_tr2 are almost the same running time, but mapl_tr2 is slightly faster.&nbsp; So we can conclude that the closure adds a very small amount of overhead, which isn&#8217;t surprising.&nbsp; What caught me off guard is that mapl_tr3 takes more than 50% longer than mapl_tr2, owing to the constant creation of tuple objects under the hood. Looks like we have a winner, mapl_tr2!</p>
<p>For completeness, the implementations of time_iter and press_enter are given below:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">#light</span></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">open</span> System</p>
<p style="margin: 0px"><span style="color: blue">open</span> System.Diagnostics</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">let</span> press_enter () =</p>
<p style="margin: 0px">&nbsp; printfn <span style="color: maroon">&#8220;Press Enter to continue&#8230;&#8221;</span></p>
<p style="margin: 0px">&nbsp; Console.ReadLine() |&gt; ignore</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">let</span> time f =</p>
<p style="margin: 0px">&nbsp; <span style="color: blue">let</span> sw = <span style="color: blue">new</span> Stopwatch()</p>
<p style="margin: 0px">&nbsp; sw.Start()</p>
<p style="margin: 0px">&nbsp; f ()</p>
<p style="margin: 0px">&nbsp; sw.Stop()</p>
<p style="margin: 0px">&nbsp; sw.Elapsed.TotalMilliseconds</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">let</span> time_iter n f =</p>
<p style="margin: 0px">&nbsp; [0 .. n]</p>
<p style="margin: 0px">&nbsp; |&gt; List.map (<span style="color: blue">fun</span> _ <span style="color: blue">-&gt;</span> time f)</p>
<p style="margin: 0px">&nbsp; |&gt; List.average</p>
</div>
<p>(time_iter can be optimized so it doesn&#8217;t create a 0..n list and uses sequence expressions&#8230;)</p>
<h4>Conclusions</h4>
<p>F# makes it really easy to write recursive functions that succinctly express our algorithms, but care must be taken to address tail recursion so that StackOverflowExceptions aren&#8217;t encountered in production code. Also, tail-recursive functions can be further optimized by ensuring that tuple objects aren&#8217;t created at each iteration, and by explicitly passing functions to inner loops and not relying on closures.</p>
<p>Whenever you write &#8220;let rec&#8221;, don&#8217;t give the Tail Recursion Police reason to take you downtown&#8230;</p>
<p>Hope that helps someone and eliminates some of the smoke/mirrors surrounding tail recursion!&nbsp; <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/LsEfiDLMjgw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/</feedburner:origLink></item>
		<item>
		<title>Assembly Information for F# Console Applications</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/tjOdhR1adwo/</link>
		<comments>http://thevalerios.net/matt/2009/01/assembly-information-for-f-console-applications/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 23:18:59 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[AssemblyInfo]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2009/01/assembly-information-for-f-console-applications/</guid>
		<description><![CDATA[Right on the heels of my last post about an AssemblyInfo.fs file for F# Libraries (DLLs), we can do the same thing for F# console applications with a slight modification.
The default F# console application contains a single Program.fs source file. By default, this puts everything in that file into a module named &#8220;Program&#8221;.
The entry point [...]]]></description>
			<content:encoded><![CDATA[<p>Right on the heels of my <a href="http://thevalerios.net/matt/2009/01/assembly-information-for-f-libraries/">last post about an AssemblyInfo.fs file for F# Libraries (DLLs),</a> we can do the same thing for F# console applications with a slight modification.</p>
<p>The default F# console application contains a single Program.fs source file. By default, this puts everything in that file into a module named &#8220;Program&#8221;.</p>
<p>The entry point of an F# console application is typically the top-most code in the last .fs file of the project.&nbsp; This leads to the standard F# programming pattern of the last file in the project (typically Program.fs) containing something along the lines of:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">&#8230;</span></p>
<p style="margin: 0px"><span style="color: blue">let</span> main () =</p>
<p style="margin: 0px">&nbsp; &#8230;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">main ()</p>
</div>
<p>Now, to add all of the assembly metadata to the project, we need to attribute the &#8220;main ()&#8221; function call with all of the attributes.&nbsp; We can&#8217;t use the &#8220;unit&#8221; operator &#8220;()&#8221; like we did in the F# Library case, since our console application actually does have an entry point that we care about.</p>
<p>We can accomplish this by moving the &#8220;main ()&#8221; line to the AssemblyInfo.fs file, requiring us to fully-qualify it to &#8220;Program.main ()&#8221; since it resides in the Program module.</p>
<p>If we add the AssemblyInfo.fs file from the previous post, it must go last, for example:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2009/01/image2.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="105" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/01/image-thumb2.png" width="217" border="0"></a> </p>
<p>Now, in Program.fs we only have:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">&#8230;</p>
<p style="margin: 0px"><span style="color: blue">let</span> main () =</p>
<p style="margin: 0px">&nbsp; &#8230;</p>
</div>
<p>And at the end of AssemblyInfo.fs we have:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">&#8230;</p>
<p style="margin: 0px">[&lt;assembly: AssemblyVersion(<span style="color: maroon">"1.0.0.0"</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyFileVersion(<span style="color: maroon">"1.0.0.0"</span>)&gt;]</p>
<p style="margin: 0px">Program.main ()</p>
</div>
<p>Just like in the library case, it would be nice if the default F# console application template included both Program.fs and AssemblyInfo.fs and included a definition for &#8220;main&#8221; to avoid any confusion as to the entry point of the application.</p>
<p>Hope that helps!</p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/tjOdhR1adwo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2009/01/assembly-information-for-f-console-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2009/01/assembly-information-for-f-console-applications/</feedburner:origLink></item>
		<item>
		<title>Assembly Information for F# Libraries</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/EeqxBZalNBA/</link>
		<comments>http://thevalerios.net/matt/2009/01/assembly-information-for-f-libraries/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 22:30:36 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[AssemblyInfo]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2009/01/assembly-information-for-f-libraries/</guid>
		<description><![CDATA[It&#8217;s standard practice for C# applications and assemblies to have metadata attached to the assembly specifying the version number, name, company, author, etc. Usually this information is specified in the Properties\AssemblyInfo.cs file.
However, F# libraries (by default) don&#8217;t have this assembly metadata, so you don&#8217;t know what version of a DLL you are looking at.&#160; For [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s standard practice for C# applications and assemblies to have metadata attached to the assembly specifying the version number, name, company, author, etc. Usually this information is specified in the Properties\AssemblyInfo.cs file.</p>
<p>However, F# libraries (by default) don&#8217;t have this assembly metadata, so you don&#8217;t know what version of a DLL you are looking at.&nbsp; For example, without assembly information, MyLibrary looks like this in the Explorer window:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2009/01/image.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="287" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/01/image-thumb.png" width="258" border="0"></a> </p>
<p>That&#8217;s not very helpful.</p>
<p>Thankfully, it&#8217;s very easy to add an AssemblyInfo.fs file to our F# library and achieve the same thing as a C# library.</p>
<p>Here&#8217;s the AssemblyInfo.fs file that you can copy/paste into your project.</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">#light</span></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">open</span> System.Reflection;</p>
<p style="margin: 0px"><span style="color: blue">open</span> System.Runtime.CompilerServices;</p>
<p style="margin: 0px"><span style="color: blue">open</span> System.Runtime.InteropServices;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: green">// General Information about an assembly is controlled through the following </span></p>
<p style="margin: 0px"><span style="color: green">// set of attributes. Change these attribute values to modify the information</span></p>
<p style="margin: 0px"><span style="color: green">// associated with an assembly.</span></p>
<p style="margin: 0px">[&lt;assembly: AssemblyTitle(<span style="color: maroon">"MyLibrary"</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyDescription(<span style="color: maroon">""</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyConfiguration(<span style="color: maroon">""</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyCompany(<span style="color: maroon">"Matt Valerio, Inc."</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyProduct(<span style="color: maroon">"MyLibrary"</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyCopyright(<span style="color: maroon">"Copyright © Matt Valerio, Inc. 2008"</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyTrademark(<span style="color: maroon">""</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyCulture(<span style="color: maroon">""</span>)&gt;]</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: green">// Setting ComVisible to false makes the types in this assembly not visible </span></p>
<p style="margin: 0px"><span style="color: green">// to COM components.&nbsp; If you need to access a type in this assembly from </span></p>
<p style="margin: 0px"><span style="color: green">// COM, set the ComVisible attribute to true on that type.</span></p>
<p style="margin: 0px">[&lt;assembly: ComVisible(<span style="color: blue">false</span>)&gt;]</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: green">// The following GUID is for the ID of the typelib if this project is exposed to COM</span></p>
<p style="margin: 0px">[&lt;assembly: Guid(<span style="color: maroon">"c95f0dd1-9182-4d48-8bc2-b6cc2bca17bc5"</span>)&gt;]</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: green">// Version information for an assembly consists of the following four values:</span></p>
<p style="margin: 0px"><span style="color: green">//</span></p>
<p style="margin: 0px"><span style="color: green">//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Major Version</span></p>
<p style="margin: 0px"><span style="color: green">//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Minor Version </span></p>
<p style="margin: 0px"><span style="color: green">//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Build Number</span></p>
<p style="margin: 0px"><span style="color: green">//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Revision</span></p>
<p style="margin: 0px"><span style="color: green">//</span></p>
<p style="margin: 0px"><span style="color: green">// You can specify all the values or you can default the Build and Revision Numbers </span></p>
<p style="margin: 0px"><span style="color: green">// by using the &#8216;*&#8217; as shown below:</span></p>
<p style="margin: 0px"><span style="color: green">// [assembly: AssemblyVersion("1.0.*")]</span></p>
<p style="margin: 0px">[&lt;assembly: AssemblyVersion(<span style="color: maroon">"1.0.0.0"</span>)&gt;]</p>
<p style="margin: 0px">[&lt;assembly: AssemblyFileVersion(<span style="color: maroon">"1.0.0.0"</span>)&gt;]</p>
<p style="margin: 0px">() </p>
</div>
<p>To use it, make AssemblyInfo.fs the last file in your F# Library (DLL) project (remember &#8211; file order is important for F# projects).&nbsp; If necessary, right click on the file and use the &#8220;Move Up&#8221; and &#8220;Move Down&#8221; commands.</p>
<p>After compiling the F# Library, it will then have all of the usual CLR metadata compiled into the assembly and show up in the Explorer window correctly:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2009/01/image1.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="287" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2009/01/image-thumb1.png" width="258" border="0"></a> </p>
<p>It is very important to note that the last line of AssemblyInfo.fs is &#8220;()&#8221;.&nbsp; The file won&#8217;t compile without this, since attributes (even though they are assembly-level attributes) must be applied to something.&nbsp; In this case, we&#8217;re applying all of the attributes to the &#8220;nothing&#8221; placeholder in F#, called &#8220;unit&#8221;, or &#8220;()&#8221;.</p>
<p>It would be nice if the F# templates that ship with the F# CTP included this file by default. I guess I could always make my own template <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Hope that helps!</p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/EeqxBZalNBA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2009/01/assembly-information-for-f-libraries/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2009/01/assembly-information-for-f-libraries/</feedburner:origLink></item>
		<item>
		<title>Project Euler, Problem 11 in F# using Pattern Matching</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/uSXGbiiulnQ/</link>
		<comments>http://thevalerios.net/matt/2008/12/project-euler-problem-11-in-f-using-pattern-matching/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 21:05:23 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[project euler]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2008/12/project-euler-problem-11-in-f-using-pattern-matching/</guid>
		<description><![CDATA[This week at the F# for Scientists Book Club we got onto the topic of Project Euler, problem 11.&#160; 
To restate the problem: 
In the 20&#215;20 grid below, four numbers along a diagonal line have been bolded.
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 [...]]]></description>
			<content:encoded><![CDATA[<p>This week at the F# for Scientists Book Club we got onto the topic of <a href="http://projecteuler.net/">Project Euler</a>, <a href="http://projecteuler.net/index.php?section=problems&amp;id=11">problem 11</a>.&nbsp; </p>
<p>To restate the problem: </p>
<blockquote><p>In the 20&#215;20 grid below, four numbers along a diagonal line have been bolded.
<p>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08<br />49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00<br />81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65<br />52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91<br />22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80<br />24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50<br />32 98 81 28 64 23 67 10 <b>26</b> 38 40 67 59 54 70 66 18 38 64 70<br />67 26 20 68 02 62 12 20 95 <b>63</b> 94 39 63 08 40 91 66 49 94 21<br />24 55 58 05 66 73 99 26 97 17 <b>78</b> 78 96 83 14 88 34 89 63 72<br />21 36 23 09 75 00 76 44 20 45 35 <b>14</b> 00 61 33 97 34 31 33 95<br />78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92<br />16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57<br />86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58<br />19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40<br />04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66<br />88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69<br />04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36<br />20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16<br />20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54<br />01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
<p>The product of these numbers is 26&#215;63x78&#215;14 = 1788696.
<p>What is the greatest product of four adjacent numbers in any direction (up, down, left, right, or diagonally) in the 20&#215;20 grid?</p>
</blockquote>
<p>We started down the path of how to extract all of the possible sequences of 4 numbers from the 20&#215;20 grid using sequence expressions.&nbsp; However, it occurred to me that pattern matching might be a good fit for this, so I decided to try out an alternative approach using pattern matching.</p>
<p>The first step is to create a pattern-matchable structure containing our 20&#215;20 grid of numbers. I decided to use an &#8220;int list list&#8221; &#8212; a list of a list of integers.&nbsp; This is easy enough to do if we split the text into lines, then split each line into number strings, and then convert each number string into an integer:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">#light</span></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">#r</span> <span style="color: maroon">&#8220;FSharp.PowerPack.dll&#8221;</span>;;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">let</span> text = </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: maroon">@&#8221;08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54</span></p>
<p style="margin: 0px"><span style="color: maroon">&nbsp;&nbsp;&nbsp; 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48&#8243;</span></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: blue">let</span> cells = </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; text </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; String.split [<span style="color: maroon">'\n'</span>]</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; List.map (String.split [<span style="color: maroon">' '</span>] &gt;&gt; List.map int)</p>
</div>
<p>In F#-ese, we take the text, and &#8220;pipe&#8221; (using the |&gt; operator) it into the String.split operation that splits the string on newlines.&nbsp; This gives us a list of strings (string list) that we can then &#8220;pipe&#8221; into a List.map operation that applies the given function to each string in the list (each row).&nbsp; This mapping function splits each row string on spaces and then converts each number string to an integer.&nbsp; I&#8217;m using function composition here (the &gt;&gt; operator), since the string split happens, and then the integer conversion happens.</p>
<p>As we&#8217;re hunting through all of the possible 4-number combinations (left-right, up-down, diagonal-left, and diagonal-right), we need to store some information.&nbsp; We need 1) the product of the 4 numbers and 2) the 4 numbers themselves.&nbsp; This seems like a good place to use a tuple, where we can store two things &#8212; the product and the 4-number list.&nbsp; We can write a function that takes 4 numbers and creates this tuple for us:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">let</span> makeTuple a b c d = (a*b*c*d, [a; b; c; d])</p>
</div>
<p>The signature of this method is &#8220;val makeTuple : int -&gt; int -&gt; int -&gt; int -&gt; int * int list&#8221;, which says that we take 4 integers and create an (int * int list), i.e. a 2-element tuple with an integer and an integer list.</p>
<p>Now we come to the pattern matching aspect of the problem.&nbsp; We need to apply a 4&#215;4 filter to the 20&#215;20 cell array, look for 4 patterns, and then repeat the process for the remaining cells.</p>
<p>Pattern matching in F# can easily dissect a list into its head (first element) and its tail (whatever&#8217;s left). This is denoted as &#8220;head::tail&#8221;.&nbsp; You can also match with more than one element out of the front of the list, using &#8220;h1::h2::h3::tail&#8221;. In addition, you can ignore things if you don&#8217;t want to explicitly give them a name by using the &#8220;I don&#8217;t care&#8221; symbol, _, e.g. &#8220;h1::h2::_&#8221;.&nbsp; And, you can group elements together and give them a new name, for example &#8220;h1::(h2::h3::_ as tail)&#8221;.</p>
<p>So, here&#8217;s the code for our pattern finding algorithm:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">let</span> <span style="color: blue">rec</span> findPatterns (cells : int list list) =</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">match</span> cells <span style="color: blue">with</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; | (a11::(a12::a13::a14::_ <span style="color: blue">as</span> t1))::</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ((a21::(a22::a23::&nbsp; _::_ <span style="color: blue">as</span> t2))::</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (a31::(a32::a33::&nbsp; _::_ <span style="color: blue">as</span> t3))::</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (a41::(&nbsp; _::&nbsp; _::a44::_ <span style="color: blue">as</span> t4))::_ <span style="color: blue">as</span> t5) <span style="color: blue">-&gt;</span> <span style="color: blue">let</span> h = makeTuple a11 a12 a13 a14</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">let</span> v = makeTuple a11 a21 a31 a41</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">let</span> d1 = makeTuple a11 a22 a33 a44</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">let</span> d2 = makeTuple a41 a32 a23 a14</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [h; v; d1; d2] :: </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (findPatterns [t1; t2; t3; t4] @</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (findPatterns t5)) <span style="color: green">//all one line</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; | _ <span style="color: blue">-&gt;</span> [[]]</p>
</div>
<p>The findPatterns function takes our cells (a list of list of integers) and performs a pattern match over them.&nbsp; The syntax is a little odd at first, so I made a picture to show what is matched with what:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/12/image2.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="415" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/12/image-thumb2.png" width="532" border="0"></a> </p>
<p>If the cells match the pattern (that is, a 4&#215;4 square has been found), then the 4-length sequences are stored as a tuple, and the method is recursively called again, twice.&nbsp; </p>
<p>The first recursive invocation is called with a new 2-d list containing the 4 tails from the previous match. In this loop, [t1; t2; t3; t4] keep getting their leftmost elements stripped out until there isn&#8217;t a 4&#215;4 square left, in which case the pattern match fails, _ is matched, an empty &#8220;list list&#8221; ([[]]) is returned, and the recursion stops.&nbsp; So basically we are walking left-to-right matching patterns and storing the results.</p>
<p>The second recursive invocation is called with the tail t5.&nbsp; This is the input cells without the first row.&nbsp; With this invocation we&#8217;re recursively walking the cells from top to bottom.</p>
<p>So, once we are able to find all of the patterns, then to solve the problem we just need to find the maximum value of the tuples returned:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">let</span> result = </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; cells</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; findPatterns</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; List.concat</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; |&gt; List.max_by fst</p>
</div>
<p>Here we invoke findPatterns with the cells (returning a list list), concatenate that down to a list (of int * int list), and then find the maximum using the first value of the tuple (the product of the 4 numbers).</p>
<p>The result is:</p>
<blockquote><p>&gt; result;;<br />val it : int * int list = (70600674, [87; 97; 94; 89])</p>
</blockquote>
<p>Cool!&nbsp; It doesn&#8217;t take any time at all to execute on my machine &#8212; well below the &#8220;1 minute rule&#8221; for Project Euler.</p>
<p>I&#8217;m sure there are ways to improve this algorithm.&nbsp; It uses the stack quite heavily, and the list concatenation (@ operator) is expensive. Also, storing all of the results for all combinations wastes memory &#8212; a fold would be more efficient, allowing you to compare as you move along.</p>
<p>Despite these potential problems, I really like this solution because it is so concise.</p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/uSXGbiiulnQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2008/12/project-euler-problem-11-in-f-using-pattern-matching/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2008/12/project-euler-problem-11-in-f-using-pattern-matching/</feedburner:origLink></item>
		<item>
		<title>Getting Started with Git on GitHub</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/1ClHp9ZHBmI/</link>
		<comments>http://thevalerios.net/matt/2008/12/getting-started-with-git-on-github/#comments</comments>
		<pubDate>Wed, 03 Dec 2008 13:49:25 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[source control]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2008/12/getting-started-with-git-on-github/</guid>
		<description><![CDATA[After the awesome F# for Scientists Book Club meeting the other night, I wanted to set up a code repository for everyone to share their code.
After some discussion on the Google Groups list, we decided to use Git instead of Subversion for the source control.&#160; Sure, why not? Might as well try out something new.&#160; [...]]]></description>
			<content:encoded><![CDATA[<p>After the awesome F# for Scientists Book Club meeting the other night, I wanted to set up a code repository for everyone to share their code.</p>
<p>After some discussion on the Google Groups list, we decided to use <a href="http://git.or.cz/">Git</a> instead of Subversion for the source control.&nbsp; Sure, why not? Might as well try out something new.&nbsp; We found <a href="http://github.com">GitHub.com</a> which offers free hosting for public projects.</p>
<h4>Installing the Git Client</h4>
<p>I hunted around for a TortoiseSVN-esque Windows client for git, but there isn&#8217;t one (yet?).&nbsp; Ah well, back to the command line with Cygwin.&nbsp; I usually have Cygwin installed, but my installation on this machine is broken for whatever reason.&nbsp; Thankfully I stumbled onto <a href="http://code.google.com/p/msysgit/downloads/list">msysgit</a>, an all-in-one installer.</p>
<p>I ran the installer, using all of the default options:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/12/image.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="385" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/12/image-thumb.png" width="503" border="0"></a> </p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/12/image1.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="385" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/12/image-thumb1.png" width="503" border="0"></a> </p>
<p>Git uses SSH under the covers to connect to the remote git repository, so we need to spend a second setting up our public/private key pairs.</p>
<p>Double-clicking on the &#8220;Git Bash&#8221; shortcut on my desktop brings me up to a MINGW32 command prompt.&nbsp; I need to generate new SSH keys, so I did:</p>
<p>$ ssh-keygen.exe</p>
<p>This generated a few files: <br />~/.ssh/id_rsa = Private key<br />~/.ssh/id_rsa.pub = Public key</p>
<p>You&#8217;ll need to cat the id_rsa.pub file and copy/paste that public key (starting with the &#8220;ssh-rsa&#8221; line) into your GitHub account next.</p>
<h4>Creating a GitHub account</h4>
<p>Just <a href="https://github.com/signup/free">sign up for a free Github account</a> (pretty self-explanatory).</p>
<p>You&#8217;ll need to provide the SSH <em>public</em> key (not the private key!) to github so that you&#8217;ll have permission to commit. You can enter the key on the first screen (it&#8217;s optional), or add one once you&#8217;ve created the account.</p>
<h4>Using Git</h4>
<p>I just followed the directions on the <a href="http://github.com/mattvalerio/fsharpbooksamples/tree/master">fsharpbooksamples project page</a>.</p>
<p>$ cd /d/OpenSource/<br />$ mkdir fsharpbooksamples<br />$ cd fsharpbooksamples/<br />$ git init</p>
<p>Here I created and edited a README.txt file</p>
<p>$ git add README.txt<br />$ git config &#8211;global user.email matt.valerio@gmail.com<br />$ git commit -m &#8216;Initial commit&#8217;<br />$ git remote add origin git@github.com:mattvalerio/fsharpbooksamples.git<br />$ git push origin master</p>
<p>And, that&#8217;s about it.&nbsp; Note that on the last push command, it will fail if you don&#8217;t have your SSH keys set up correctly. It will complain with an error message that says &#8220;Permission denied (publickey)&#8221;.&nbsp; If you set up a passphrase while generating your SSH keys, you&#8217;ll need to enter that here.</p>
<p>Hope that helps! <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/1ClHp9ZHBmI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2008/12/getting-started-with-git-on-github/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2008/12/getting-started-with-git-on-github/</feedburner:origLink></item>
		<item>
		<title>Exception Handling, Queuing, and UI Synchronization for WCF Services Using the CCR</title>
		<link>http://feedproxy.google.com/~r/ValerioDotNet/~3/-qpWgZRcflw/</link>
		<comments>http://thevalerios.net/matt/2008/11/exception-handling-queuing-and-ui-synchronization-for-wcf-services-using-the-ccr/#comments</comments>
		<pubDate>Mon, 17 Nov 2008 22:30:16 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[ccr]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[threading]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[winforms]]></category>

		<guid isPermaLink="false">http://thevalerios.net/matt/2008/11/exception-handling-queuing-and-ui-synchronization-for-wcf-services-using-the-ccr/</guid>
		<description><![CDATA[This weekend I wanted to throw together a nice sample illustrating some ideas that I was playing around with this summer. While I was out at Microsoft Research, I got turned onto Microsoft Robotics Developer Studio and the incredibly cool Concurrency and Coordination Runtime (CCR) that gives it a solid foundation.
Interacting with remote services is [...]]]></description>
			<content:encoded><![CDATA[<p>This weekend I wanted to throw together a nice sample illustrating some ideas that I was playing around with this summer. While I was out at Microsoft Research, I got turned onto <a href="http://msdn.microsoft.com/en-us/robotics/default.aspx">Microsoft Robotics Developer Studio</a> and the incredibly cool <a href="http://www.microsoft.com/ccrdss/">Concurrency and Coordination Runtime (CCR)</a> that gives it a solid foundation.</p>
<p>Interacting with remote services is difficult.&nbsp; WCF has made the interaction easier using the &#8220;address-binding-contact&#8221; abstractions, but this doesn&#8217;t address things like concurrency , multithreading, asynchronicity, failures, and timeouts. Writing code that handles all of the possible scenarios can be messy very quickly. ThreadPools, BeginInvoke, EndInvoke, IAsyncResult, ManualResetEvent, and friends aren&#8217;t exactly the easiest thing to get right, but if you want a responsive UI and a robust application, you <em>must</em> worry about all of these things.</p>
<p>George Chrysanthakopoulos and the creators of the CCR recognized this and have provided an amazing abstraction on top of the current threading implementations on the .NET platform. I&#8217;ve <a href="http://thevalerios.net/matt/2008/08/paradigm-shift-designing-asynchronous-programs-using-the-ccr/">blogged</a> <a href="http://thevalerios.net/matt/2008/10/ccr-101-download-available/">about</a> <a href="http://thevalerios.net/matt/2008/10/microsoft-ccr-and-dss-toolkit-2008/">the CCR</a> <a href="http://thevalerios.net/matt/2008/06/multithreading-and-concurrency-in-net/">before</a>, but haven&#8217;t really posted any useful examples that truly illustrate its power. Get ready to be blown away &#8212; I&#8217;m going to show how easy it is to write a WinForms client that accesses a remote WCF service that:</p>
<ul>
<li>Correctly interacts with the UI on the correct thread
<li>Has full responsiveness of the UI
<li>Caches requests to the service if necessary
<li>Never blocks a thread while waiting for something, performing all operations asynchronously
<li>Never uses the &#8220;lock&#8221; keyword</li>
</ul>
<p>I couldn&#8217;t believe how easy it was to get everything working. </p>
<h4>The WCF Service</h4>
<p>I&#8217;ve just made an extremely simple WCF Service for this demo.&nbsp; It has a single operation, DoSomething that takes a request and generates a response. I like the way that the DoSomethingRequest and DoSomethingResponse allow for both multiple input and output properties on the respective types, making for a cleaner interface. Apparently <a href="http://davybrion.com/blog/2008/07/the-request-response-service-layer/">I&#8217;m not the only one to think this</a>, though the motivation is grounds for another complete post.</p>
<p>Our WCF service is contained within a WCF Service Library. This makes it easy to reference from other projects in the solution.</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">[<span style="color: #2b91af">ServiceContract</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IUsefulService</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af">OperationContract</span>]</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">DoSomethingResponse</span> DoSomething(<span style="color: #2b91af">DoSomethingRequest</span> request);</p>
<p style="margin: 0px">}</p>
</div>
<p>The request/response classes are very straightforward:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">[<span style="color: #2b91af">DataContract</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">DoSomethingRequest</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> DoSomethingRequest(<span style="color: blue">int</span> inputValue)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.InputValue = inputValue;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; } </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af">DataMember</span>]</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: blue">int</span> InputValue { <span style="color: blue">get</span>; <span style="color: blue">private</span> <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">}</p>
</div>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">[<span style="color: #2b91af">DataContract</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">DoSomethingResponse</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> DoSomethingResponse(<span style="color: blue">string</span> outputValue)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.OutputValue = outputValue;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af">DataMember</span>]</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: blue">string</span> OutputValue { <span style="color: blue">get</span>; <span style="color: blue">private</span> <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">}</p>
</div>
<p>The implementation of the service is also very simple:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">[<span style="color: #2b91af">ServiceBehavior</span>(InstanceContextMode=<span style="color: #2b91af">InstanceContextMode</span>.PerCall, ConcurrencyMode=<span style="color: #2b91af">ConcurrencyMode</span>.Multiple)]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">UsefulService</span> : <span style="color: #2b91af">IUsefulService</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">DoSomethingResponse</span> DoSomething(<span style="color: #2b91af">DoSomethingRequest</span> request)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Do something useful [sic]</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Thread</span>.Sleep(500);</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// We REALLY don&#8217;t like 2 (reminds us of the clowns&#8230;)</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (request.InputValue == 2)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ArgumentException</span>(<span style="color: #a31515">&#8220;UsefulService: The input value may not be 2!!&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">string</span> message = <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">&#8220;UsefulService: Just did something useful with: {0}&#8221;</span>, request.InputValue);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> <span style="color: blue">new</span> <span style="color: #2b91af">DoSomethingResponse</span>(message);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">}</p>
</div>
<p>The service just takes in a request (an integer) and returns a response (a string) with more text.&nbsp; However, if the input is 2, then an exception is thrown, so we&#8217;ll need to be ready on the client to handle this. (We&#8217;re ignoring fault contracts now for simplicity).</p>
<p>I should also point out that this service has InstanceContextMod=PerCall.&nbsp; This means that WCF instantiates a new instance of the UsefulService class for every call that comes in. Also, we have ConcurrencyMode=Multiple, indicating that WCF also uses a new thread for every incoming call (with a preset maximum number that I can&#8217;t remember at the moment).&nbsp; What this does is essentially blow the WCF service host wide open in terms of concurrency, allowing multiple threads to interact with their own instance of the class.&nbsp; Since we&#8217;re not doing anything requiring synchronized access to shared state, these settings are largely unimportant.</p>
<p>Note that I&#8217;m not using the CCR on the service side &#8212; not yet.&nbsp; I have some examples of how to do this, but that will unfortunately have to wait for future post <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Now onto the client&#8230;</p>
<h4>The WCF Client</h4>
<p>On the client side (a WinForms project), we add a reference to the service, making sure to go into the advanced option and turn on the generation of asynchronous operations.</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/11/image29.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="436" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/11/image-thumb29.png" width="535" border="0"></a> </p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/11/image30.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="517" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/11/image-thumb30.png" width="551" border="0"></a> </p>
<p>This automatically generates a UsefulServiceClient class that not only has synchronous methods DoSomething, but also a method/event pair that can be used to invoke the operation asynchronously:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/11/image31.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="297" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/11/image-thumb31.png" width="165" border="0"></a> </p>
<p>We&#8217;ll use the method/event pair for this example and won&#8217;t worry about using the Begin/End methods.</p>
<p>&lt;Sidenote&gt;</p>
<p>It&#8217;s also interesting to note that our generated IUsefulService interface on the client actually has 3 methods instead of 1 (with the attributes, cruft and unnecessary namespaces removed):</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IUsefulService</span> {</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af">OperationContractAttribute</span>(Action=<span style="color: #a31515">"..."</span>, ReplyAction=<span style="color: #a31515">"..."</span>)]</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">DoSomethingResponse</span> DoSomething(<span style="color: #2b91af">DoSomethingRequest</span> request);</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af">OperationContractAttribute</span>(AsyncPattern=<span style="color: blue">true</span>, Action=<span style="color: #a31515">"..."</span>, ReplyAction=<span style="color: #a31515">"..."</span>)]</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; System.<span style="color: #2b91af">IAsyncResult</span> BeginDoSomething(<span style="color: #2b91af">DoSomethingRequest</span> request, <span style="color: #2b91af">AsyncCallback</span> callback, <span style="color: blue">object</span> asyncState);</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">DoSomethingResponse</span> EndDoSomething(<span style="color: #2b91af">IAsyncResult</span> result);</p>
<p style="margin: 0px">}</p>
</div>
<p>We could also use the {Begin/End}DoSomething pair here (also exposed on the UsefulServiceClient) since WCF can handle the APM (Asynchronous Programming Model pattern of the framework) invocation under the covers.&nbsp; I&#8217;ll dig into this in a future post when we get to using the CCR on the server side. If you&#8217;re interested, <a href="http://www.danrigsby.com/blog/index.php/2008/03/18/async-operations-in-wcf-event-based-model/">Dan Rigsby has an excellent series of posts</a> about asynchronous WCF service implementation. I&#8217;ll talk about this more in a future post.</p>
<p>&lt;/Sidenote&gt;</p>
<h4>CCR-Compatible WCF Client Wrapper</h4>
<p>I&#8217;m not going to go into much detail here (check out <a href="http://thevalerios.net/matt/2008/08/paradigm-shift-designing-asynchronous-programs-using-the-ccr/">this post</a> to get started) about the architecture of the CCR. Suffice it to say that we have our very own thread pool, the DispatcherQueue, not related in any way to the .NET ThreadPool.&nbsp; We create any number of &#8220;ports&#8221; which are just strongly-typed queues that can have messages &#8220;posted&#8221; to them.&nbsp; Then, we can hook up handlers that get called whenever a message gets posted to the port.&nbsp; The sender and receiver are completely decoupled, and the thread which executes the handler is managed by the dispatcher.</p>
<p>The key thing to take away from this is that ports (aptly named) are the &#8220;interfaces&#8221; between the producer and the consumer.&nbsp; So, if we want to communicate with a service, we ask it for a port with which to post incoming requests for it to operate on.&nbsp; On a similar token, we can also request a reference to a port with which we can hook up a handler to be called whenever the service obtains a response.</p>
<p>So, we can create a wrapper class around the auto-generated WCF client class that exposes two ports &#8212; an input (request) and an output (response) port.</p>
<p>Well, that&#8217;s the idea anyway.&nbsp; Unfortunately we&#8217;ve subtly overlooked our failure scenarios.&nbsp; Another possible outcome of a call to the service is that an exception is thrown.&nbsp; The CCR allows us to create a conglomerate of ports called a PortSet which allows us to specify that either of two message types can be posted there.&nbsp; We need this for the output port since the outcome of our operation could either be a response or an exception. This is a great approach since the <em>failure information is explicit</em> &#8212; we don&#8217;t have to wonder if an exception will just &#8220;bubble up&#8221; later.</p>
<p>Another point that needs to be made is that the CCR operates under a message-passing paradigm which emphasizes statelessness. Every message is self-contained.&nbsp; So, we could post message requests into a port and wait for message responses on another port, but because of the asynchronous nature of things, we can&#8217;t assume that the response order will match the request order.&nbsp; If we need to know which request generated which response (as is the case here), we need to be more explicit. The solution isn&#8217;t difficult &#8212; we just bundle a request with its response and call it a DoSomethingContext:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">DoSomethingContext</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">DoSomethingRequest</span> Request { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">DoSomethingResponse</span> Response { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">}</p>
</div>
<p>This brings us to the first glimpse of our UsefulServiceWrapper class:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">UsefulServiceWrapper</span> : <span style="color: #2b91af">CcrServiceBase</span></p>
<p style="margin: 0px">{ </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> UsefulServiceWrapper(<span style="color: #2b91af">DispatcherQueue</span> queue)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : <span style="color: blue">base</span>(queue)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px"><span style="color: green">// &#8230;</span></p>
<p style="margin: 0px"><span style="color: green"></span>&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">Port</span>&lt;<span style="color: #2b91af">DoSomethingContext</span>&gt; DoSomethingInputPort {<span style="color: blue">get&#8230;}</span></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">PortSet</span>&lt;<span style="color: #2b91af">DoSomethingContext</span>, <span style="color: #2b91af">Exception</span>&gt; DoSomethingOutputPort {<span style="color: blue">get&#8230;}</span></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">Port</span>&lt;<span style="color: blue">string</span>&gt; LogPort {<span style="color: blue">get&#8230;}</span>&nbsp;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: green">// &#8230;</span></p>
<p style="margin: 0px">}</p>
</div>
<p>We notice that our wrapper inherits from CcrServiceBase, a lightweight base class that just provides a TaskQueue property that exposes a DispatcherQueue which is set in the constructor, as well as a few other convenience methods.&nbsp; We need to have access to the application&#8217;s DispatcherQueue to be able to send and receive messages through the ports.</p>
<p>There are three ports (or Ports/PortSets to be particular) here.&nbsp; The first port is the input to the DoSomething operation which takes a DoSomethingContext (in this case the Request property will have a non-null DoSomethingRequest and the Response property will be null). The second port is a PortSet of a DoSomethingContext and an Exception, indicating that there are 2 possible outcomes of the operation.&nbsp; The third port is a convenience port which allows the internal workings of the wrapper class to be observed (if desired) by allowing log messages to be posted to it.</p>
<h4>Wrapper Logic</h4>
<p>While implementing the wrapper logic, we have one rule &#8212; NEVER block a thread while we&#8217;re waiting for WCF to do something.&nbsp; If we&#8217;re not doing something constructive with the thread (a scarce resource), then let the CCR execute other code with it.</p>
<p>Consequently, the standard WCF client convention is completely out: </p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: #2b91af">UsefulServiceClient</span> client = <span style="color: blue">new</span> <span style="color: #2b91af">UsefulServiceClient</span>();</p>
<p style="margin: 0px">client.Open();</p>
<p style="margin: 0px">client.DoSomething(request);</p>
<p style="margin: 0px">client.Close();</p>
</div>
<p>This ties up a single thread during the entire execution of the operation.&nbsp; If there&#8217;s a lot of network delay, I wouldn&#8217;t be surprised if 99% of the time the thread is sitting there idle, waiting for a response. This really limits our scalability in a big way. This isn&#8217;t going to work work &#8212; we need to use the asynchronous equivalent for everything &#8212; {Begin/End}Open, DoSomethingAsync/DoSomethingCompleted, and {Begin/End}Close.</p>
<p>Let&#8217;s take a look at just the constructor operation.&nbsp; We&#8217;re going to use an awesome feature of the CCR &#8211; <a href="http://msdn.microsoft.com/en-us/library/bb648753.aspx">CCR Iterators</a> &#8212; that uses C# 2.0 iterators to write synchronous-<em>looking</em> code that executes asynchronously.&nbsp; The trick is to implement a method that returns IEnumerator&lt;ITask&gt;.&nbsp; ITask is just a &#8220;unit of work&#8221; for the CCR, and we return an enumeration.&nbsp; We get to use the yield keyword inside of iterator methods.</p>
<p>When you think about it, iterators are methods that execute different code each time that you call them.&nbsp; That is exactly why they are well-suited for doing asynchronous programming &#8212; the individual sections of the method can be executed by different threads in an asynchronous manner as they are needed. The compiler works its magic behind the scenes, actually implementing iterators as a state machine. Pretty cool stuff.</p>
<p>Here&#8217;s the first part of the implementation showing how we can execute the constructor and catch any exceptions:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">private</span> <span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: #2b91af">ITask</span>&gt; DoSomethingIterator(<span style="color: #2b91af">DoSomethingContext</span> context)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">bool</span> failed = <span style="color: blue">false</span>;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">SuccessFailurePort</span> successFailurePort = <span style="color: blue">new</span> <span style="color: #2b91af">SuccessFailurePort</span>();</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// Try to call constructor</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">UsefulServiceClient</span> client = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">try</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; client = <span style="color: blue">new</span> <span style="color: #2b91af">UsefulServiceClient</span>();</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(<span style="color: blue">new</span> <span style="color: #2b91af">SuccessResult</span>());&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> ex)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(ex);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">yield</span> <span style="color: blue">return</span> <span style="color: #2b91af">Arbiter</span>.Choice(successFailurePort,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (successResult) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Client creation successful.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (failureException) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Client creation failed.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_DoSomethingOutputPort.Post(failureException);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (failed) <span style="color: blue">yield</span> <span style="color: blue">break</span>;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// &#8230; rest of the code</span></p>
<p style="margin: 0px">}</p>
</div>
<p>First we create a SuccessFailurePort, just a fancy name for PortSet&lt;SuccessResult,Exception&gt;. Then we try to call the constructor inside of a try/catch block. If the constructor completes successfully, then we post a success result to the success/failure port.&nbsp; If an exception occurs, then we post the exception to the port.&nbsp; The next line is where the magic of the CCR comes in &#8212; we &#8220;yield return Arbiter.Choice(successFailurePort&#8230;)&#8221;.&nbsp; Translated into english, this means: &#8220;Return this thread back to the CCR and don&#8217;t come back until EITHER a success result OR an exception gets posted to the successFailurePort. Then, when we&#8217;ve &#8216;joined&#8217; up with either result, execute either of these next two anonymous methods depending on which one was posted.&#8221;&nbsp; Whoa.&nbsp; That&#8217;s an amazing amount of power right there, after you get used to the unfamiliar syntax.</p>
<p>So, If there is a successful result, a message is posted to the log and the method continues down.&nbsp; If there is an exception, we post a message to the log and also post the exception to the DoSomethingOutputPort, and set the failed flag to true.&nbsp; If that flag is set, then we &#8220;yield break&#8221;, indicating to the CCR that we are completely finished with this method and never expect to re-enter the iterator. When we yield break, we&#8217;re completely done.</p>
<p>(Bear with me &#8212; even though this looks like a lot of code, it&#8217;s boilerplate. I&#8217;ve written a T4 template for generating it.&nbsp; Also, there are less verbose ways of calling things (thanks to some extension methods in the latest version) but they can be difficult to grasp without first seeing things like this. We&#8217;ll see soon that interacting with this code via the ports is a breeze, so it&#8217;s worth it to write it once and forget about it.)</p>
<p>Now, assuming that the constructor didn&#8217;t throw an exception, we can now open the client (asynchronously of course):</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">client.InnerChannel.BeginOpen(</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (iar) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">try</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; client.InnerChannel.EndOpen(iar);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(<span style="color: blue">new</span> <span style="color: #2b91af">SuccessResult</span>());&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> ex)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(ex);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }, <span style="color: blue">null</span>);</p>
<p style="margin: 0px"><span style="color: blue">yield</span> <span style="color: blue">return</span> <span style="color: #2b91af">Arbiter</span>.Choice(successFailurePort,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (successResult) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Open successful.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; },</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (failureException) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Open failed.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_DoSomethingOutputPort.Post(failureException);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; });</p>
<p style="margin: 0px"><span style="color: blue">if</span> (failed) <span style="color: blue">yield</span> <span style="color: blue">break</span>;</p>
</div>
<p>This pattern should look familiar &#8212; it is the standard method of interacting with APM code.&nbsp; The trick is that the EndXXX method can always throw an exception if the operation failed, so we need to handle that in the same way as before with the successFailurePort. Notice that if we have two possible paths (e.g. success or failure) then both paths must be capable of posting something to the port to be able to continue past the Choice.</p>
<p>Now we can interact with the DoSomethingAsync operation.&nbsp; First we subscribe to the even handler, call the method, and then wait for either success or failure:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: green">// Now try to call DoSomething asynchronously</span></p>
<p style="margin: 0px">client.DoSomethingCompleted += (sender, args) =&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">try</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (args.Cancelled == <span style="color: blue">true</span>)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(<span style="color: blue">new</span> <span style="color: #2b91af">Exception</span>(<span style="color: #a31515">&#8220;The operation was cancelled.&#8221;</span>));</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (args.Error != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(args.Error);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; context.Response = args.Result;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(<span style="color: blue">new</span> <span style="color: #2b91af">SuccessResult</span>());</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> ex)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(ex);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">};</p>
<p style="margin: 0px">client.DoSomethingAsync(context.Request);</p>
<p style="margin: 0px"><span style="color: green">// Wait until the operation EITHER succeeds or fails</span></p>
<p style="margin: 0px"><span style="color: blue">yield</span> <span style="color: blue">return</span> <span style="color: #2b91af">Arbiter</span>.Choice(successFailurePort,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (successResult) =&gt; </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Operation successful&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; },</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (failureException) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Operation failed.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_DoSomethingOutputPort.Post(failureException);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; });</p>
<p style="margin: 0px"><span style="color: blue">if</span> (failed) <span style="color: blue">yield</span> <span style="color: blue">break</span>;</p>
</div>
<p>Once again, if there was a failure then the exception is posted to the output port and we &#8220;yield break&#8221; indicating that the iterator method has completed (completely).</p>
<p>As the last step, we then call {Begin,End}Close:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: green">// Now try to call BeginClose asynchronously</span></p>
<p style="margin: 0px">client.InnerChannel.BeginClose(</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (iar) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">try</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; client.InnerChannel.EndClose(iar);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(<span style="color: blue">new</span> <span style="color: #2b91af">SuccessResult</span>());</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> ex)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; successFailurePort.Post(ex);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }, <span style="color: blue">null</span>);</p>
<p style="margin: 0px"><span style="color: green">// Wait until the operation EITHER succeeds or fails</span></p>
<p style="margin: 0px"><span style="color: blue">yield</span> <span style="color: blue">return</span> <span style="color: #2b91af">Arbiter</span>.Choice(successFailurePort,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (successResult) =&gt; </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Close successful.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; },</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; (failureException) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_LogPort.Post(<span style="color: #a31515">&#8220;Close failed.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_DoSomethingOutputPort.Post(failureException);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; });</p>
<p style="margin: 0px"><span style="color: blue">if</span> (failed) <span style="color: blue">yield</span> <span style="color: blue">break</span>;</p>
</div>
<p>If we make it this far in the iterator method, then we are finished and a successful result has been stored in the DoSomethingContext.&nbsp; We can then post the completed context (containing both the request and the response of the DoSomething method) to the output port:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: green">// If we made it this far, then the result was obtained </span></p>
<p style="margin: 0px"><span style="color: green">// successfully and we can post it to the output port.</span></p>
<p style="margin: 0px">m_DoSomethingOutputPort.Post(context);</p>
<p style="margin: 0px"><span style="color: blue">yield</span> <span style="color: blue">break</span>;</p>
</div>
<p>And&#8230;we&#8217;re done. Almost.</p>
<p>The only thing missing is how we specify that DoSomethingIterator contains all of the code to run when something is posted to the DoSomethingInputPort.&nbsp; To do this, we need to &#8220;activate&#8221; a &#8220;receiver&#8221; on the input port &#8212; that is, wire up the input port so that it runs the iterator. In this case, it&#8217;s as easy as putting this in the constructor:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: #2b91af">Arbiter</span>.Activate(<span style="color: blue">this</span>.TaskQueue,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Arbiter</span>.ReceiveWithIterator(<span style="color: blue">true</span>, m_DoSomethingInputPort, DoSomethingIterator)</p>
<p style="margin: 0px">);</p>
</div>
<p>The TaskQueue property refers to the DispatcherQueue given to the wrapper class&#8217;s constructor.</p>
<p>Now that we have the verbose part out of the way, let&#8217;s take a look at how we can use our CCR-compatible wrapper class by interfacing through its ports.</p>
<h4>The WinForms Client</h4>
<p>Ok, now we get to the fun part. <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  So far we have implemented a service, auto-generated a WCF proxy to the service, and created a wrapper class around the WCF proxy.&nbsp; Now all we need to do is create a form to illustrate how to use our CCR WCF wrapper class.</p>
<p>The form is simple: 1 input text box, 1 button, and a scrolling output text box.</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/11/image32.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="346" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/11/image-thumb32.png" width="450" border="0"></a> </p>
<p>When I press the Send button, I want to fire off N simultaneous requests to the WCF service with the request payload counting from 1 to N. When a request comes back, I want to log some information in the bottom text box.&nbsp; I also want to handle all service exceptions, and I want to be able to move the window around while the service calls are being executed without having redraw problems.</p>
<p>Ok, so we&#8217;re faced with an interesting scenario here: to be CCR-compatible, we need to use the CCR&nbsp; DispatcherQueue (essentially a thread pool), but how can we do that when WinForms has very specific threading requirements to handle the underlying Win32 API interop (message pump, etc)?</p>
<p>The trick is that the CCR comes with a number of WinForms adapters that make this impedance mismatch easier to handle.&nbsp; Unfortunately I didn&#8217;t find everything that I needed in the Microsoft.Ccr.Adapters.WinForms namespace, so I needed to write a little more interface code.&nbsp; The result is a programming API that directly mimics a typical WinForms program.&nbsp; Normally the Program.cs file contains:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">[<span style="color: #2b91af">STAThread</span>]</p>
<p style="margin: 0px"><span style="color: blue">static</span> <span style="color: blue">void</span> Main()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Application</span>.EnableVisualStyles();</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Application</span>.SetCompatibleTextRenderingDefault(<span style="color: blue">false</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Application</span>.Run(<span style="color: blue">new</span> <span style="color: #2b91af">MainForm</span>());</p>
<p style="margin: 0px">}</p>
</div>
<p>However, I&#8217;ve written a CcrApplication.Run static method so that we can do this instead:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">[<span style="color: #2b91af">STAThread</span>]</p>
<p style="margin: 0px"><span style="color: blue">static</span> <span style="color: blue">void</span> Main()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Application</span>.EnableVisualStyles();</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Application</span>.SetCompatibleTextRenderingDefault(<span style="color: blue">false</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">CcrApplication</span>.Run((queue) =&gt; <span style="color: blue">new</span> <span style="color: #2b91af">MainForm</span>(queue));</p>
<p style="margin: 0px">}</p>
</div>
<p>That&#8217;s not so bad.&nbsp; The only trick here is that instead of passing in a Form argument to Application.Run is that we&#8217;re passing in a Func&lt;DispatcherQueue,CcrForm&gt; delegate.&nbsp; This is just a method that takes a DispatcherQueue and returns a CcrForm.&nbsp; What is this CcrForm, you ask?</p>
<p>It&#8217;s just an abstract base class that accepts a DispatcherQueue in the constructor and uses that queue to set everything up. The key here is that the CcrForm has a property called FormServicePort of type WinFormsServicePort that lets us interact with the form (create a new one, invoke delegates on the UI thread, and close down the form).</p>
<p>I modified the code from <a href="http://www.dotnetjunkies.com/WebLog/wimdc/archive/2006/11/3.aspx">this post</a> so that it correctly handles form shutdown. The CcrApplication.Run method just creates a DispatcherQueue and then initializes a ManualResetEvent that we can wait on to keep the main thread from exiting (otherwise our window wouldn&#8217;t even show). We also hook up to the FormClosed event on the form so that we can cleanly shut down. </p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">CcrApplication</span></p>
<p style="margin: 0px">{</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">DispatcherQueue</span> m_DispatcherQueue;</p>
<p style="margin: 0px"><span style="color: green">// &#8230;</span></p>
</div>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">void</span> Run(<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">DispatcherQueue</span>, <span style="color: #2b91af">CcrForm</span>&gt; createForm)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (createForm == <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&#8220;createForm&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">using</span> (<span style="color: #2b91af">Dispatcher</span> dispatcher = <span style="color: blue">new</span> <span style="color: #2b91af">Dispatcher</span>(0, <span style="color: #a31515">&#8220;Dispatcher&#8221;</span>))</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">using</span> (m_DispatcherQueue = <span style="color: blue">new</span> <span style="color: #2b91af">DispatcherQueue</span>(<span style="color: #a31515">&#8220;DispatcherQueue&#8221;</span>, dispatcher))</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Create the form using the newly-created dispatcher</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">CcrForm</span> form = createForm(m_DispatcherQueue);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// &#8230;</span></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">
<p style="margin: 0px"><span style="color: green"></span></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">ManualResetEvent</span> mainThreadEvent = <span style="color: blue">new</span> <span style="color: #2b91af">ManualResetEvent</span>(<span style="color: blue">false</span>);
</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; form.FormClosed +=</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (sender, args) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Shutdown</span> shutdown = <span style="color: blue">new</span> <span style="color: #2b91af">Shutdown</span>();</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Sign up to be notified when the WinFormServicePort</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// has successfully been shutdown</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Arbiter</span>.Activate(m_DispatcherQueue,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Arbiter</span>.Choice(shutdown.ResultPort,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (success) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mainThreadEvent.Set();</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (failure) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mainThreadEvent.Set();</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; })</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// We need to inform the WinFormsAdaptor that it is ok to quit.</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; form.FormServicePort.Post(shutdown);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Use the WinFormsServicePort to create a MainForm.</span></p>
<p style="margin: 0px">
<p style="margin: 0px"><span style="color: green"></span></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; form.FormServicePort.Post(<span style="color: blue">new</span> <span style="color: #2b91af">RunForm</span>(() =&gt; form));
</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Wait for the form to be closed</span></p>
<p style="margin: 0px"><span style="color: green"></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mainThreadEvent.WaitOne();</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">}</p>
</div>
<p>The CcrForm class is also fairly straightforward, just storing the DispatcherQueue so that we can use it from the form.</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">partial</span> <span style="color: blue">class</span> <span style="color: #2b91af">CcrForm</span> : <span style="color: #2b91af">Form</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> CcrForm(<span style="color: #2b91af">DispatcherQueue</span> taskQueue)</p>
</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : <span style="color: blue">base</span>()</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; InitializeComponent();</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (taskQueue == <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">InvalidOperationException</span>(<span style="color: #a31515">&#8220;The taskQueue is null.&nbsp; Make sure that you are using the CcrApplication.Run method to start the main message loop.&#8221;</span>);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.TaskQueue = taskQueue;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.FormServicePort = <span style="color: #2b91af">WinFormsAdapter</span>.Create(taskQueue);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">DispatcherQueue</span> TaskQueue { <span style="color: blue">get</span>; <span style="color: blue">private</span> <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: #2b91af">WinFormsServicePort</span> FormServicePort {<span style="color: blue">get</span>; <span style="color: blue">private</span> <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: blue">void</span> Activate(<span style="color: blue">params</span> <span style="color: #2b91af">ITask</span>[] tasks)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Arbiter</span>.Activate(<span style="color: blue">this</span>.TaskQueue, tasks);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">
<p style="margin: 0px"><span style="color: gray"></span></p>
<p>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: blue">void</span> FormInvoke(<span style="color: #2b91af">Action</span> action)
</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.FormServicePort.Post(<span style="color: blue">new</span> <span style="color: #2b91af">FormInvoke</span>(() =&gt; action()));</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">}</p>
</div>
<p>The Activate method is just for convenience so we don&#8217;t need to keep typing this.TaskQueue.&nbsp; The FormInvoke method also makes calling it easier (as we&#8217;ll see in a sec).</p>
<h4>Client Logic</h4>
<p>Ok, we&#8217;re almost there! We need to &#8220;wire up&#8221; the logic in the form:</p>
<ul>
<li>Whenever a message is posted to the log port, display the information in the bottom text box
<li>Whenever a message is posted to the service output port (successfully), display the result in the bottom text box
<li>Whenever a message is posted to the service output port (exception), display the exception message in the bottom text box
<li>Whenever the Send button is pressed, post messages to the service input port.</li>
</ul>
<p>The first 3 are receivers, and then last 1 is a post.&nbsp; We can set up the first three persistent receivers in the constructor like this:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: green">// Create the CCR wrapper for the WCF service so that it dispatches to our main queue</span></p>
<p style="margin: 0px">m_Service = <span style="color: blue">new</span> <span style="color: #2b91af">UsefulServiceWrapper</span>(<span style="color: blue">this</span>.TaskQueue);</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px"><span style="color: green">// Wire up the logic:</span></p>
<p style="margin: 0px"><span style="color: blue">this</span>.Activate(</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// If anything comes in on the log port,</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Arbiter</span>.Receive(<span style="color: blue">true</span>, m_Service.LogPort,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// then write it to the output</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (message) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Log(<span style="color: #a31515">&#8220;Log&nbsp;&nbsp; : {0}&#8221;</span>, message);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }),</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// If a string result comes in on the output port,</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Arbiter</span>.Receive(<span style="color: blue">true</span>, m_Service.DoSomethingOutputPort.P0,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// then write it to the output</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (result) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Log(<span style="color: #a31515">&#8220;Result: {0}&#8221;</span>, result.Response.OutputValue);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }),</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// If an error comes in on the result port,</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Arbiter</span>.Receive(<span style="color: blue">true</span>, m_Service.DoSomethingOutputPort.P1,</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// then write it to the output</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (error) =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Log(<span style="color: #a31515">&#8220;Error : {0}&#8221;</span>, error.Message);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; })</p>
<p style="margin: 0px">);</p>
</div>
<p>The Log method is just a helper method that appends a line of text to the lower textbox by wrapping the code up into a delegate and posted it to the WinFormsServicePort so that it may be executed on the UI thread.</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">private</span> <span style="color: blue">void</span> Log(<span style="color: blue">string</span> format, <span style="color: blue">params</span> <span style="color: blue">object</span>[] args)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: green">// Invoke the AppendText method on the UI thread</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.FormInvoke(</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; () =&gt;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; txtOutput.AppendText(</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">&#8220;[{0}]:{1}{2}&#8221;</span>, </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">DateTime</span>.Now.ToLongTimeString(), </p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">String</span>.Format(format, args),</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">Environment</span>.NewLine));</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; );</p>
<p style="margin: 0px">}</p>
</div>
<p>The only thing we have left is the button handler which posts new messages to the service input port:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: consolas">
<p style="margin: 0px"><span style="color: blue">private</span> <span style="color: blue">void</span> btnSend_Click(<span style="color: blue">object</span> sender, <span style="color: #2b91af">EventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span> numThreads;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (<span style="color: #2b91af">Int32</span>.TryParse(txtInput.Text, <span style="color: blue">out</span> numThreads))</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (numThreads &gt; 50) numThreads = 50;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (numThreads &lt; 2) numThreads = 2;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">for</span> (<span style="color: blue">int</span> i = 0; i &lt; numThreads; i++)</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// post the number into the input port of the service</span></p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">DoSomethingContext</span> ctx = <span style="color: blue">new</span> <span style="color: #2b91af">DoSomethingContext</span>()</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Request = <span style="color: blue">new</span> <span style="color: #2b91af">DoSomethingRequest</span>()</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; InputValue = i</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_Service.DoSomethingInputPort.Post(ctx);</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px">}</p>
</div>
<p>There&#8217;s an arbitrary limit of 50 messages in there, just so you can&#8217;t go completely nuts (100,000 requests might be a bit much).</p>
<h4>Testing</h4>
<p>After all of that work, we can finally try things out! I set my solution so that both my WinForms project and my WCF service get started when I hit F5.</p>
<p>The WCF test client starts up, indicating our service is live:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/11/image33.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="275" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/11/image-thumb33.png" width="588" border="0"></a> </p>
<p>Now we dial in 10 as the number of threads to start and click the Send button.&nbsp; Not just once.&nbsp; 20 times.&nbsp; I just totally wail on the Send button and watch what happens:</p>
<p><a href="http://thevalerios.net/matt/wp-content/uploads/2008/11/image34.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="375" alt="image" src="http://thevalerios.net/matt/wp-content/uploads/2008/11/image-thumb34.png" width="586" border="0"></a> </p>
<p>After about 20 seconds, all of the queued requests finally finish and all log lines get printed to the text box.&nbsp; Amazingly, I was able to constantly move the window around my screen <em>without any hiccups</em> as all of that was going on! And, to think that all of that happened without writing a single line of lock synchronization code&#8230;</p>
<h4>Conclusion</h4>
<p>I hope you enjoyed this in-depth exploration into the amazing world of the CCR.&nbsp; I know I sure did. I&#8217;m quickly becoming a fan of the CCR&#8217;s model of event-driven asynchronous programming, where you can define your interfaces between components and then just &#8220;wire them up&#8221; with receiver code.&nbsp; It certainly makes for a clean model.</p>
<p>To recap, we were able to write clean code that correctly interacted with the UI thread, giving us a fully-responsive UI, were able to cache the service requests by posting them into the wrapper&#8217;s input port, and we NEVER blocked a thread while waiting for asynchronous I/O. In addition, all failure conditions were handled cleanly. The code might seem pretty complicated at first (lots of anonymous methods everywhere) but after you get used to the way things work, it&#8217;s very powerful.&nbsp; The ability to write synchronous-looking code that executes asynchronously is (to put it simply) pure genius on George&#8217;s part.</p>
<p>One thing that I didn&#8217;t cover is the CCR&#8217;s ability to coordinate lock-style code (e.g. to access shared state).&nbsp; I&#8217;ll take an in-depth look into coordination/synchronization, as well as how to use the CCR to implement asynchronous WCF <em>services</em> in a future post.</p>
<p>I&#8217;ll put up the code soon for everyone to download.</p>
<p>Hope that helps! <img src='http://thevalerios.net/matt/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/ValerioDotNet/~4/-qpWgZRcflw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://thevalerios.net/matt/2008/11/exception-handling-queuing-and-ui-synchronization-for-wcf-services-using-the-ccr/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://thevalerios.net/matt/2008/11/exception-handling-queuing-and-ui-synchronization-for-wcf-services-using-the-ccr/</feedburner:origLink></item>
	</channel>
</rss>
