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

<channel>
	<title>.NET Reflector &#187; Blog</title>
	<atom:link href="http://www.reflector.net/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.reflector.net</link>
	<description>The world&#039;s most downloaded .NET decompiler</description>
	<lastBuildDate>Mon, 14 May 2012 09:38:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Understanding async code with .NET Reflector</title>
		<link>http://www.reflector.net/2012/05/understanding-async-code-net-reflector/</link>
		<comments>http://www.reflector.net/2012/05/understanding-async-code-net-reflector/#comments</comments>
		<pubDate>Thu, 03 May 2012 07:46:00 +0000</pubDate>
		<dc:creator>Clive</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Version 7.6]]></category>
		<category><![CDATA[WinRT]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=3286</guid>
		<description><![CDATA[Yesterday, I gave an overview of the problems that async solves, and how it actually solves them. As we saw in that post, async is remarkably cunning, and can become remarkably tricky to follow when applied in a real application, which naturally makes any decompilation a bit of a challenge. If you haven&#8217;t read the [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/05/understanding-async-code-net-reflector/' callback='wdgpo_plusone_click'></g:plusone></div> <p>Yesterday, I gave an overview of the problems that async solves, and how it actually solves them. As we saw in that post, async is  remarkably cunning, and can become remarkably tricky to follow when applied in  a real application, which naturally makes any decompilation a bit of a  challenge. If you haven&#8217;t read <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0LzIwMTIvMDUvaG93LWRvZXMtYXN5bmMtd29yay8="><strong>the previous post on how async works </strong></a>already, I recommend you at least skim  through it so that you know what examples we&#8217;ll be working with, and so that  we&#8217;re all working with the same understanding of state machines. </p>
<p>  Now, with that introduction done, we should have a look at  some real code. </p>
<p><span id="more-3286"></span></p>
<p>  We are currently implementing support for the decompilation  of async inside .NET Reflector, so all the code you&#8217;ll see in this post will be  generated by Reflector, both before and after the translation phase that deals  with the <b>async state machines</b>. </p>
<p style="padding-left:20px"><i>  You need to be aware that there  are several implementations of async in the code that we&#8217;ll see, because there  are different implementations of async in the code that you find in the .NET  4.5 framework libraries compared with code that is compiled using the Dev11 C#  5 compiler.  For our Reflector work we  are currently working on the former, mainly because the fundamental part of the  work (the processing of the state machine) is the same in both cases, and the  framework libraries contain hundreds of potential test cases.</i></p>
</blockquote>
<h2 style="padding-top:5px">Real code</h2>
<p>If you look at the <b>ReadAsyncInternal</b> method in the .NET 4.5 version of <b>mscorlib</b>,  you&#8217;ll see that it has the following code:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDUvMVJlYWRBc3luY0ludGVybmFsLnBuZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/1ReadAsyncInternal_sml.png" alt="the ReadAsyncInternal method in the .NET 4.5 version of mscorlib" width="540" height="226" border="0" /></a><br />
<i>Click for an enlarged version</i></p>
<p>Remember, from our earlier example of the simple  string-reader program, the compiler generates a class which implements the  state machine, setting the various fields corresponding to the arguments and  the local variables, which get lifted into this class. The <b>&lt;&gt;t__builder</b> is an instance of <b>AsyncTaskMethodBuilder</b>, which is used to do the plumbing between  the client and the implementation of the async method, and we&#8217;ll see it used in  the <b>MoveNext</b> method.</p>
<p>  The compiler-generated class has the following form: </p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDUvMkFzeW5jVGFza01ldGhvZEJ1aWxkZXIucG5n"><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/2AsyncTaskMethodBuilder_sml.png" alt="The compiler-generated class in the MoveNext method" width="540" height="375" border="0" /></a><br />
<i>Click for an enlarged version</i></p>
<p>  Notice the state value field <b>&lt;&gt;1__state</b>, and the field <b>&lt;&gt;4__ this</b> which allows access back to the original instance  of <b>StreamReader</b> which constructed  this instance of the state machine.</p>
<p>  For us, the really interesting part is the code in the <b>MoveNext</b> method:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDUvM01vdmVOZXh0LnBuZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/3MoveNext_sml.png" alt="the code in the MoveNext method" width="540" height="444" border="0" /></a><br />
<i>Click for an enlarged version</i></p>
<p>  The outer <b>Try</b> has  a body that ends with the code:</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/4OuterTry.png" alt="The outer Try in the MoveNext method." width="424" height="154" border="0" /></p>
<p> Let&#8217;s take a quick walk through the implications of this.</p>
<h2 style="padding-top:5px">Stepping through the code</h2>
<p>In the exception case we set the state to -1, which is a  state that causes the <b>MoveNext</b> to  return instantly while remaining in that state. In the success case, we store  the function result value using the <b>SetResult</b>,  which ends up setting the value into the <b>Task</b> associated with this invocation of the method. Likewise, the <b>SetException</b> sets the <b>Exception</b> property of the <b>Task</b> object, taking care to specially handle  the <b>OperationCanceledException</b>,  which is used by the <b>Task</b> library to  communicate that a synchronous cancellation request was successfully honoured.  After this, anyone waiting on the <b>Task</b> will be notified that they can continue running via the usual implementation in  the <b>Task</b> class.</p>
<p>  It&#8217;s fairly easy to follow the code around while keeping an  eye on the state transitions, but the most interesting thing that happens occurs  when we call out to some asynchronous method, such as in the following code  fragment:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDUvNUFzeW5jaHJvbm91cyBDYWxsb3V0LnBuZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/5Asynchronous-Callout_sml.png" alt="Calling out to some asynchronous method." width="540" height="291" border="0" /></a><br />
<i>Click for an enlarged version</i></p>
<p>  Our method is calling into the <b>ReadAsync</b> method:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDUvNlJlYWRBc3luYy5wbmc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/6ReadAsync_sml.png" alt="Calling into the ReadSync method." width="540" height="74" border="0" /></a><br />
<i>Click for an enlarged version</i></p>
<p>  This returns a <b>Task</b> which will eventually contain a count of the number of bytes read, potentially  also modifying the arrays that were passed in as arguments. </p>
<p>  We now get a slight complication. In order to control  whether the synchronization context and other information needs to be  preserved, the <b>Task</b> is passed  through the .<b>ConfigureAwait</b> method  before its <b>GetAwaiter</b> is called.  This result of the call to <b>GetAwaiter()</b> supports the <b>Await</b> pattern; it is  expected to have certain methods implemented on it, much like an <b>Enumerable</b> is expected to have a <b>GetEnumerator</b> method. Let&#8217;s take a look  at how this process can proceed.</p>
<p>  First we have the quick path: when <b>IsCompleted</b> returns true to say that the result is already  available, we can jump straight to label <b>03AD</b>.  Otherwise, things get a little more complicated: we need to save any state  we&#8217;re going to need later into a field in the current object, set up the <b>OnCompleted</b> action of the task so that  the <b>MoveNext</b> method is going to be  called again, set the state field to the next state, and return. At some point,  assuming no exceptions, we&#8217;ll be called back, the state value will ensure that  we reach label <b>0390</b>, where we can  get back the values that we saved away, and then continue to the same place  that we&#8217;d have gone in the fast path. </p>
<p>  At that location, we&#8217;ll get the result of the asynchronous  operation using <b>GetResult</b> and carry  on as if we had been running all the time. Notice that all of the thread  transitions (if any are required) are hidden away inside the object that is  returned by <b>GetAwaiter</b>, which is  responsible for getting us to the right place before it calls the delegate that  was passed into <b>OnCompleted</b>.</p>
<h2 style="padding-top:5px">Not one compiler, but two</h2>
<p>As I mentioned earlier, part of the challenge in understand  all this comes as a result that we&#8217;re targeting at least two, subtly different,  compilers. Thus far we&#8217;ve been looking at the results of the compiler used to  generate the .NET 4.5 framework libraries, so how does this all change if you  use the compiler that ships with the latest Dev11 beta?</p>
<p>  First there is now an interface, <b>IAsyncStateMachine</b>, that constrains the interface between the state  machine and the code that uses it:</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/7IAsyncStateMachine.png" width="423" height="101" alt="The IAsyncStateMachine interface." /></p>
<p>  This is implemented by the compiler generated type which is  now a struct instead of a class:</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/8CompilerGeneratedType.png" width="437" height="288" alt="IAsyncStateMachine implemented by the compiler-generated type." /></p>
<p>  The initialization code also looks a little different:</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/9InitializationCode.png" width="446" height="189" alt="IAsyncStateMachine initialization code." /></p>
<p>  The body of the <b>MoveNext</b> is still surrounded by a <b>Try Catch</b> block as before, though the code to fire off an asynchronous call now has  slightly fewer lines to it, using the builder to do more of the work. As  before, if the operation doesn&#8217;t instantly complete, the state is set, and we  set up a notification from the called method so that we&#8217;ll be brought back  after the operation completes. In order to do this, we need to pass in the awaiter  and the state machine object by using the ref modifier on the call:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDUvMTBBd2FpdGVyLnBuZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/10Awaiter_sml.png" alt="Passing in the awaiter using the ref modifier." width="540" height="151" border="0" /></a><br />
<i>Click for an enlarged version</i>  </p>
<p>  The idea is the same as the previous implementation, though  the mechanics of capturing the relevant synchronization and execution contexts  is a little different. If you want to see what I mean, take a look at the code  in the <b>AsyncTaskmethodBuilder</b> class  in <b>System.Runtime.CompilerServices</b> in the .NET 4.5 version of <b>mscorlib.dll</b>.</p>
<p>  By looking out for the pattern of Async code, Reflector can  fold code back into the form using async/await. So, for example, the above  example will be displayed as:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDUvMTFBc3luY0RlY29tcGlsZWQucG5n"><img src="http://www.reflector.net/blog/wp-content/uploads/2012/05/11AsyncDecompiled_sml.png" alt="Async decompilation." width="540" height="321" border="0" /></a><br />
<i>Click for an enlarged version</i></p>
<h2 style="padding-top:5px">Summary</h2>
<p>Async is implemented using a compiler transform to implement  code as a state machine, though this requires a few support classes in the  runtime library, and that a set of methods need to be implemented on types that  support asynchronous calls following the <b>Await</b> pattern. No changes are required to the CLR, though some support has been added  inside <b>mscorlib</b>, and extra methods have  been added to the <b>Task&lt;…&gt;</b> type  to support the calls of the Awaiter pattern.</p>
<p>  From the point of view of a tool like Reflector, having the  compiler do a transform, rather than implementing the feature as something  built into the CLR, unsurprisingly makes life harder for a decompiler. There&#8217;s  no metadata to say some set of IL instructions are here as the result of the  translation of an <b>await</b>, so instead  the decompiler needs to look for the pattern of calls that is generated by the  C# compiler. This is exactly the kind of thing that is already done to  recognise lambda expressions and iterator blocks, which are also implemented by  the compiler rather than the CLR. Given that, as we saw in the previous post, a  basic state machine can be lashed together using lambda expressions and  iterator blocks, the similarities in the both the implementation and our  solution are no surprise.</p>
<p>  Async really seems to have hit the sweet spot for a  technology that allows you to fairly transparently run non-blocking code on a single  thread, and user code looks very much like it would for a straightforward  blocking implementation. In fact, you can almost write it that way first, and then  change it into non-blocking code by just changing the method&#8217;s return type to <b>Type&lt;…&gt;</b>, marking it with async,  and then using <b>await</b> and asynchronous  versions of methods that you call.</p>
<p> Naturally, it isn&#8217;t quite that simple in practice. For  example, having a function return too early might not interact well with  constructs such as locks and exception handlers, and potentially offers the  chance of re-entrancy in cases that were previously safe. Nevertheless, async  is not as opaque as perhaps it first seems, and you could learn a huge amount  by using .NET Reflector to start investigating C#5 as soon as possible.</p>
<p><a href= "http://www.microsoft.com/visualstudio/11/en-us/downloads" target= "_blank"><img src="/blog/wp-content/uploads/2012/05/Get-VS-11-Beta.png"></a></p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3286" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/05/understanding-async-code-net-reflector/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Async: what is it for, and how does it work?</title>
		<link>http://www.reflector.net/2012/05/how-does-async-work/</link>
		<comments>http://www.reflector.net/2012/05/how-does-async-work/#comments</comments>
		<pubDate>Wed, 02 May 2012 21:48:51 +0000</pubDate>
		<dc:creator>Clive</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[async]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=3263</guid>
		<description><![CDATA[C# 5 has finally arrived, and the biggest new feature in the language is async, and its associated Await (contextual) keyword. Naturally, there&#8217;s been a lot of discussion from a lot of different points of view, and we&#8217;ve been working hard to make sure .NET Reflector can accurately decompile asynchronous code so that you can [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/05/how-does-async-work/' callback='wdgpo_plusone_click'></g:plusone></div> <p>C# 5 has finally arrived, and the biggest new feature in the language is async, and its associated <b>Await</b> (contextual) keyword. Naturally, there&#8217;s been a lot of discussion from a lot of different points of view, and we&#8217;ve been working hard to make sure .NET Reflector can accurately decompile asynchronous code so that you can start investigating C#5 code right away. Just understanding how async actually works at the front end is no mean feat, and when you bear in mind that we&#8217;re juggling up to 3 different compilers, it&#8217;s been a fascinating challenge.</p>
<p> Before we dive into how we&#8217;re handing async code in Reflector, it&#8217;s worth grounding ourselves first. Let&#8217;s start with a quick look at what async is designed for, and then we&#8217;ll take a deeper dive into the nuts and bolts, and how they apply to us.</p>
<p><span id="more-3263"></span></p>
<h2 style="padding-top:5px"> Solving a problem</h2>
<p> This much-anticipated Async feature is designed to solve a problem that every developer has run into when writing a GUI application &#8211; GUI locking &amp; freezing. Most windowing libraries avoid the need to take locks by having all of the GUI code run on a single thread, with this thread using some kind of mailbox to prevent asynchronous message arrival. </p>
<p> We obviously want to prevent asynchronous message arrival because, when the string of a TextBox is being updated to &#8220;fred&#8221;, we don&#8217;t want to get a message telling us to update it to &#8220;joe&#8221; while we are still in the middle of processing the change to &#8220;fred&#8221;. The key to this enforcement of linear processing is that the GUI is only going to respond to user interaction if the single GUI-owned thread is available to do processing of incoming events. If we need to do a blocking operation, like hitting a web service, and we do it on the GUI-owned thread, then the GUI is going to feel dead, with screen updates and actions not having any effect until the blocking operation finishes. </p>
<p> This is unacceptable, particularly on touch controlled devices, where the feedback has to be quick to be effective. Visiting some sites on my iPhone&#8217;s web browser can be painful, as I often touch to cause some kind of action, but then find that Safari is still busy processing the page. Frustratingly, this leaves me in a state where I don&#8217;t know if Safari is going to do something when it gets less busy, or whether my earlier interaction has just been ignored. WinRT is going to be designed for touch from day one, and its designers have apparently paid careful attention to existing touch Operating Systems, and learned some valuable lessons. As a result, WinRT requires all operations that are going to take more than 50 milliseconds to offer an asynchronous version (and, in lots of cases, only an asynchronous version), as a means of keeping the user experience of Metro applications slick and intuitive. The question then becomes how to make it easy for developers to use this new functionality.</p>
<h2 style="padding-top:5px"> New tricks</h2>
<p> In the past we&#8217;ve been able to defer work to a later point in time by capturing the context as a closure, passing this closure to some object that is responsible for doing the wait, and then having that closure called when the code should continue running. This continuation-passing style makes the code very complicated to read, and makes it very hard to follow the control flow of the code. </p>
<p> Let&#8217;s take a look at an example of this using a very simplistic example. Suppose we want to read two strings from the Console, and write their total length in characters to the Console. If at any point a blank line is entered, then we don&#8217;t want to read any more data, but we still want to print the total number of characters:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas">
         <span style='color:blue'>int </span>totalCharacters</span> = 0;</span><br />
         </span><span style='color:blue'>string</span> input = <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />       </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input))<br />       </span>{<br />           </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;First string: {0}&quot;</span>, input);<br />           </span>totalCharacters</span> += input.Length</span>;<br />           </span>input</span> = <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />           </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input))<br />           </span>{<br />               </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;Second string: {0}&quot;</span>, input);<br />            </span>   </span>totalCharacters</span> += input.Length</span>;<br />           </span>}<br />       </span>}<br />       </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span>totalCharacters</span>);<br /><span style='font-size:9.5pt;font-family:Consolas'>&nbsp;</span></p>
<p>The trouble with the above code is that it is blocking the main thread, which doesn&#8217;t matter in this case, but would if it were an operation on the GUI. The thread also sits inside <b>Console.ReadLine</b>, consuming the resources that a thread requires (such as 1mb of stack space), without doing any useful work. If this was some kind of (web) server application, then this would be wasteful and would inhibit scalability. Ideally, we&#8217;d really like to record the state of the program, but then pass the thread back to the runtime, only grabbing it later when we have more work to do.</p>
<p> Let&#8217;s say we were provided with some kind of asynchronous version of <b>Console.ReadLine</b>, such as a function of the following form, which takes responsibility for getting data from the console and then calling an action function with that data when it is available on some available thread:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas"><span style='color:blue'>static</span> <span style='color:blue'>void</span> ReadLineAndThenDo</span>(<span style='color:#2B91AF'>Action</span>&lt;<span style='color:blue'>string</span>&gt;action)<br />              </span>{<br />
              </span><span style='color:#2B91AF'>ThreadPool</span>.QueueUserWorkItem</span>(</span><br />               </span><span style='color:blue'>delegate</span><br />                   </span>{<br />                        </span><span style='color:blue'>string</span> line = <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />                        </span>action(</span>line);<br />                   </span>});<br />        </span>}</p>
<p>In that situation, it would be possible for the outer function to release the thread it is running on, knowing that the action function is going to be called on a suitable thread when the result is available.</p>
<p>There are two ways that you might implement the new program. You might use the continuation-passing style we briefly mentioned earlier, using lambda expressions to capture the state of the local variables, which we can use for later parts of the computation:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas"><span style='color:blue'>static</span> <span style='color:blue'>void</span> ReadLineAndThenDo</span>(<span style='color:#2B91AF'>Action</span>&lt;<span style='color:blue'>string</span>&gt;action)<br />        </span>{<br />            </span><span style='color:#2B91AF'>ThreadPool</span>.QueueUserWorkItem</span>(</span><br />               </span><span style='color:blue'>delegate</span><br />                   </span>{<br />                        </span><span style='color:blue'>string</span> line = <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />                        </span>action(</span>line);<br />                   </span>});<br />        </span>}</p>
<p>In that situation, it would be possible for the outer function to release the thread it is running on, knowing that the action function is going to be called on a suitable thread when the result is available.
<p>There are two ways thatyou might implement the new program. You might use the continuation-passingstyle we briefly mentioned earlier, using lambda expressions to capture thestate of the local variables, which we can use for later parts of thecomputation:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas"><span style='color:blue'>static</span> <span style='color:blue'>void</span> Attempt2()<br />
  {<br />
     </span><span style='color:blue'>int</span> totalCharacters</span>= 0;<br />
        </span>ReadLineAndThenDo</span>(</span><br />
           </span>input</span> =&gt;<br />
              </span>{<br />
                 </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input))<br />
                 </span>{<br />
                     </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;First string: {0}&quot;</span>,input);<br />
                     </span>totalCharacters</span> += input.Length</span>;<br />
                     </span>ReadLineAndThenDo</span>(</span><br />
                       </span>input2 =&gt;<br />
                         </span>{<br />
                           </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input2))<br />
                           </span>{<br />
                             </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&#8220;Second string: {0}&#8221;</span>,input2);<br />
                             </span>totalCharacters</span> += input2.Length;<br />
             </span>              </span>}<br />
                           </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span>totalCharacters</span>);<br />
                         </span>});<br />
                 </span>}<br />
               </span>});<br />
  }
</p>
<p>In this instance, the change has been localised to our function, but what a change it is! Every time we want to do an asynchronous call, we have had to pass in the rest of the code as a lambda expression (input =&gt; &#8230;) or (input2 =&gt; &#8230;). The indentation gets deeper and deeper, and things become very complicated if we have a loop construct of any kind in the code. The logic of the code has been obfuscated in order to fit into the programming language.</p>
<p>However, if we take another look at the very first version of our string reader, we can see that there are distinct sections of code, with a new section starting each time we pass control to a <b>ReadLine</b>. For example, we start in state one, which does the initial setup of the local variables, and we then do a <b>ReadLine</b> and assume we enter state two when this has finished. As we enter state two, we know that there is new input available, and we can process this until we get to the next <b>ReadLine</b>, which starts state three:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas">            </span>/*State 0 */<br />            </span><span style='color:blue'>int</span>totalCharacters</span> = 0;<br />            </span><span style='color:blue'>string</span> input = <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />           </span>/* State 1 */<br />            </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input))<br />            </span>{<br />               </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;First string: {0}&quot;</span>,input);<br />               </span>totalCharacters</span> += input.Length</span>;<br />               </span>input</span> = <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />               </span>/* State 2 */<br />               </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input))<br />               </span>{<br />                   </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;Second string: {0}&quot;</span>,input);<br />                   </span>totalCharacters</span> += input.Length</span>;<br />               </span>}<br />            </span>}<br />     </span>/* State 3 */<br />            </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span>totalCharacters</span>);<br />&nbsp;</p>
<p>This feels very much like what is known as a <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9GaW5pdGUtc3RhdGVfbWFjaGluZQ=="><b>state machine</b></a> in Computer Science parlance, which is the second way we can implement this program. We&#8217;ve seen such implementations used before, in the compilation of iterator blocks by the C# compiler, so there is already existing compiler technology for implementing such transformations.</p>
<p>We can implement the state machine using a new compiler generated class, <b>Attempt3Machine</b>. This will have a state variable, <b>m_State</b>, recording the state of the machine as one of its fields. We&#8217;ll lift the local variables of the method into the fields of the state machine (necessary because they live between the calls into our state machine), and we&#8217;ll implement the machine in a way that uses a single method to transition it from its current state to the next state. We call this method <b>MoveNext</b>, in the spirit of iterator blocks implementation.</p>
<h2>Implementing a state machine</h2>
<p> We&#8217;ll now need to change our asynchronous version of <b>ReadLine</b> to interact with our state machine. For the moment, the <b>ReadLine</b> will read a line from the Console, set this into the <b>m_Input field</b> which corresponds to the local variable input in the original code, and will then force the machine to make a transition:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas">        </span><span style='color:blue'>static</span> <span style='color:blue'>void</span> ReadLineAndThenDo2(<span style='color:#2B91AF'>Attempt3Machine</span>stateMachine</span>)<br />        </span>{<br />            </span><span style='color:#2B91AF'>ThreadPool</span>.QueueUserWorkItem</span>(</span><br />               </span><span style='color:blue'>delegate</span><br />                   </span>{<br />                        </span><span style='color:blue'>string</span> line = <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />                        </span>stateMachine.m_Input</span>= line;<br />                        </span>stateMachine.MoveNext</span>(</span>);<br />                   </span>});<br />        </span>}</p>
<p>This then leaves us with a state machine with the following implementation:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas">        </span><span style='color:blue'>class</span> <span style='color:#2B91AF'>Attempt3Machine</span><br />        </span>{<br />            </span><span style='color:blue'>int</span>m_State</span> = 0;<br /><span style='font-size:9.5pt;font-family:Consolas'>&nbsp;<br />            </span><span style='color:blue'>private</span> <span style='color:blue'>int</span> m_TotalCharacters</span>= 0;<br />            </span><span style='color:blue'>public</span> <span style='color:blue'>string</span> m_Input</span>;<br /><span style='font-size:9.5pt;font-family:Consolas'>&nbsp;<br />            </span><span style='color:blue'>public</span> <span style='color:blue'>void</span> MoveNext()<br /> </span>           </span>{<br />               </span><span style='color:blue'>switch</span> (m_State</span>)<br />               </span>{<br />                   </span><span style='color:blue'>case</span> 0:<br />                        </span>m_State</span>= 1;<br />                        </span>ReadLineAndThenDo2(</span><span style='color:blue'>this</span>);<br />                        </span><span style='color:blue'>return</span>;<br /><span style='font-size:9.5pt;font-family:Consolas'>&nbsp;<br />                   </span><span style='color:blue'>case</span> 1:<br />                        </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(m_Input</span>))<br />                        </span>{<br />                            </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;First string: {0}&quot;</span>,m_Input</span>);<br />                            </span>m_TotalCharacters</span>+= m_Input.Length</span>;<br />                            </span>m_State</span>= 2;<br />                            </span>ReadLineAndThenDo2(</span><span style='color:blue'>this</span>);<br />                            </span><span style='color:blue'>return</span>;<br />                        </span>}<br />                        </span><span style='color:blue'>goto</span> <span style='color:blue'>case</span> 3;<br /><span style='font-size:9.5pt;font-family:Consolas'>&nbsp;<br />                   </span><span style='color:blue'>case</span> 2:<br />                        </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(m_Input</span>))<br /> </span>                       </span>{<br />                            </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;Second string: {0}&quot;</span>,m_Input</span>);<br />                            </span>m_TotalCharacters</span>+= m_Input.Length</span>;<br />                        </span>}<br />                        </span><span style='color:blue'>goto</span> <span style='color:blue'>case</span> 3;<br /><span style='font-size:9.5pt;font-family:Consolas'>&nbsp;<br />                   </span><span style='color:blue'>case</span> 3:<br />                        </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span>m_TotalCharacters</span>);<br />                        </span><span style='color:blue'>return</span>;<br />               </span>}<br />            </span>}<br />        </span>}</p>
<p>And with a method that uses this of the form:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas">        </span><span style='color:blue'>static</span> <span style='color:blue'>void</span> Attempt3()<br />        </span>{<br />            </span><span style='color:blue'>new</span> <span style='color:#2B91AF'>Attempt3Machine</span>().MoveNext();<br />        </span>}<br /><span style='font-size:9.5pt;font-family:Consolas'>&nbsp;</span></p>
<h2>Results</h2>
<p> So where has this got us? Well, the translation between the code above and something that started out like the following is fairly mechanical:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas">            </span><span style='color:blue'>int</span> totalCharacters</span> = 0;<br />            </span><span style='color:blue'>string</span> input = <span style='color:red'>await</span> <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />            </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input))<br />            </span>{<br />                </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;First string: {0}&quot;</span>, input);<br />                </span>totalCharacters</span> += input.Length</span>;<br />                </span>input</span> = <span style='color:red'>await</span> <span style='color:#2B91AF'>Console</span>.ReadLine</span>();<br />                </span><span style='color:blue'>if</span> (!<span style='color:blue'>string</span>.IsNullOrEmpty</span>(input))<br />                </span>{<br />                    </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span><span style='color:#A31515'>&quot;Second string: {0}&quot;</span>, input);<br />                    </span>totalCharacters</span> += input.Length</span>;<br />                </span>}<br />            </span>}<br />            </span><span style='color:#2B91AF'>Console</span>.WriteLine</span>(</span>totalCharacters</span>);</p>
<p>The position of the <b>Await</b> expressions tells us where we need to have new states for the state machine, and we simply need to push the code in-between into the relevant state transition blocks. </p>
<p>By using the <b>Await</b> in the above code, we have kept the code in a state where it is easy to follow the control flow, even though the method stops running at the point where the await is called.</p>
<h2 style="padding-top:5px">Tidying up with Tasks</h2>
<p> There are, of course, several loose ends to tidy up. First, it looks easy in the above code to split the code into the transitions on a line by line basis, but in reality you can put multiple <b>Await</b> expressions in a single statement:</p>
<p style="line-height:20px; font-size:9.5pt; font-family:Consolas">            <span style='color:blue'>int</span>   x = <span style='color:red'>await</span> <span style='color:red'>f</span>()   + <span style='color:red'>await</span> <span style='color:red'>g</span>();  </p>
<p>This means we may need a new field location to store the result of the first <b>Await</b> while we are waiting for the second Await to complete. We could use several locations, or just have a single location that stores the intermediate value typed as an object, and then cast as necessary when wanting to use this value. The current semantics of await only allow a single outstanding call at any time, so we need to wait for <b>f()</b> to finish before<b> g()</b> is launched.</p>
<p> If we have an async function, then the caller needs to have something that they can use to get the value when it is finally calculated. .NET 4 included the rather brilliant <b>Task&lt;&gt; </b>abstraction, which reflects a computation that may still be running. A <b>Task&lt;int&gt;</b> object, for example, represents a calculation that may eventually return an integer. Using its Result property, a client can fish out the result value, blocking until it is available, and find out details of any exceptions that were thrown. Tasks support a number of very powerful operators, such as a <b>ContinueWith</b> (which allows you to schedule the execution of one task when some other task completes), and a means of waiting for one or many tasks to finish. Tasks also support a model of synchronous cancellation, with the user function being expected to regularly check for a demand for cancellation, and throwing an exception if this is required. As a result, any method that uses await must either return <b>void</b> or <b>Task&lt;&#8230;&gt;</b>.</p>
<h2 style="padding-top:5px">Some Considerations</h2>
<p> Threading always adds complication to any design, and our current example doesn&#8217;t really have a good threading model. Some operations need to be called on certain threads, so our code would really need to transition back onto one of these threads before it is called, probably by using the Post operation of the synchronization context that was active when we launched the asynchronous call. .NET also has a notion of an execution context which may need to flow across to any worker threads that are launched. We may need to capture these values when we launch a call, and then get back to the correct state before we restart in the next transition.</p>
<p>Exceptions also need to handled and stored away in the <b>Task</b> object associated with the current method, so that callers can later get the correct details of what went wrong. If the method finishes successfully, we&#8217;re also going to need to store the result away in the task, or at least mark the task as finished if there is no return value. This will allow callers to wait on our method finishing. </p>
<p>There are also several missing pieces in the story of the communication between the state machine (when it fires off the asynchronous work) and the object that is going to do the work. The example above hacked this, by having the asynchronous method we were calling (<b>DoReadLineAndThenDo</b>) know lots of detail about the caller, such as the field in which to write the return value. This code is obviously too specific, and is purely for demonstration purposes. We get around this by adding indirection, having the asynchronous <b>ReadLine</b> return a Task, and then hook an <b>OnCompletion</b> action to the returned task which causes the state machine to move to the next state. </p>
<p>Also, the action may complete really quickly, or might even have finished already. In that case it is a real waste of effort to go through the mechanism of returning from MoveNext and then having a <b>MoveNext</b> transition called by an external party. We could have simply jumped to the new state in the MoveNext implementation itself, without going through the capture state and then restore process. This is handled, as we&#8217;ll see in my next blog post, by having an Awaiter pattern which includes the asynchronous object, providing a property called <b>IsCompleted</b> which can be used to allow the <b>MoveNext</b> to instantly transition to the next state. The result will be fetched using <b>GetResult</b>.</p>
<h2 style="padding-top:5px">Wrapping up</h2>
<p> So asynchronous code is clearly incredibly useful, and remarkably cunning in its implementation, which means that we&#8217;ve had to work twice as hard to unravel it at the other end (as I&#8217;ll demonstrate shortly). Hopefully you can see how quickly async code can start to become convoluted, and how backtracking the various calls and state transitions in a real application poses a challenge. Now that we&#8217;re all on the same page, <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0LzIwMTIvMDUvdW5kZXJzdGFuZGluZy1hc3luYy1jb2RlLW5ldC1yZWZsZWN0b3Iv" title=\"Understanding async code with .NET Reflector\"><b>let&#8217;s take a look at how we&#8217;re handling async in .NET Reflector decompilation</b></a>.</p>
<p><a href= "http://www.microsoft.com/visualstudio/11/en-us/downloads" target= "_blank"><img src="/blog/wp-content/uploads/2012/05/Get-VS-11-Beta.png"></a></p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3263" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/05/how-does-async-work/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EAP 7.6 Build 4</title>
		<link>http://www.reflector.net/2012/04/eap-7-6-build-4/</link>
		<comments>http://www.reflector.net/2012/04/eap-7-6-build-4/#comments</comments>
		<pubDate>Tue, 24 Apr 2012 16:38:16 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=3213</guid>
		<description><![CDATA[The team is finally back under the same roof (back from assorted conferences and holidays), and we&#8217;ve been forging ahead with our Dev11 theming and C#5 async support. We also took the time to do a little house-keeping, which I&#8217;ll get out of the way first. So here&#8217;s what we&#8217;ve been working on for .NET [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/04/eap-7-6-build-4/' callback='wdgpo_plusone_click'></g:plusone></div> <p>The team is finally back under the same roof (back from assorted conferences and holidays), and we&#8217;ve been forging ahead with our Dev11 theming and C#5 async support. We also took the time to do a little house-keeping, which I&#8217;ll get out of the way first. So here&#8217;s what we&#8217;ve been working on for .NET Reflector v7.6.0.356EAP4&#8230;</p>
<p><span id="more-3213"></span></p>
<h2 style="padding-top: 5px;">House-keeping</h2>
<ul>
<li>The &#8220;about&#8221; box in the standalone component of Reflector has been given an overdue lick of paint. It&#8217;s now the same as what the Visual Studio extension displays.</li>
<li>We&#8217;ve made the availability of the niche languages more configurable. Going through the <strong>Tools &gt; Options &gt; Languages</strong> menu in the standalone tool, you can now control whether Delphi and Oxygene are available in the languages drop-down menu as decompilation targets.</li>
</ul>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvc2NyZWVuc2hvdDEuanBn"><img class="aligncenter size-full wp-image-3218" title="decompilation target language controls" src="http://www.reflector.net/blog/wp-content/uploads/2012/04/screenshot1_sml.jpg" alt="Control whether niche languages are viable decompilation targets" width="540" height="270" /></a><br />
<em>(click for a larger, clearer image)</em></p>
<ul>
<li>The End-of-EAP dialog has had a refresh, and now gives you clear instructions on how to submit your feedback, jump up to the latest Early Access build, or uninstall the EAP entirely.</li>
<li>Clive fixed a bug in the WinMD support, so that WinMD files are now discoverable on both 32-bit and 64-bit machines.</li>
</ul>
<h2 style="padding-top: 5px;">Visual Studio 11 theming</h2>
<p>Nigel&#8217;s been unravelling how theming works in VS11, and how to make the .NET Reflector components that extend into Visual Studio play nicely with the Dev11 beta. This has involved a certain degree of re-plumbing in the Reflector UI, but Nigel is taking it all in his stride.</p>
<ul>
<li>We&#8217;ve got to a point where the Reflector Object Browser and context menus accept the Dev11 theme tones &amp; background colours, so the Reflector extension should feel pretty natural inside Visual Studio.</li>
<li>At the moment, we are aware of a minor bug when using the dark theme; some text in the ROB is rendered lighter than expected. We&#8217;re tracking this down, and will get it tidied up soon.</li>
</ul>
<h2 style="padding-top: 5px;">Async decompilation</h2>
<p>Clive &amp; Ruchika are continuing to work down the list of 192 new async methods, making sure we emit sensible decompiled code in each case. Ruchika has got her head around how to effectively test async decompilation, which should start to speed things up.</p>
<ul>
<li>Taking a look at our current coverage, we support most of the new async methods in the System.IO namespace &amp; some of the new methods in System.Xml. We don&#8217;t yet support the new methods in System.net or System.Web, but these are on the list for the next sprint.</li>
<li>At the moment, we know Reflector doesn&#8217;t handle nested <strong>try</strong> blocks very well, and we&#8217;ve also taken steps to make sure we don&#8217;t emit anything totally mad. <em>Essentially, anything that we&#8217;re not sure we can do right for .NET 4.5, we fail back to emitting in .NET 4.0 (I&#8217;ll come back to this in a moment). </em></li>
</ul>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvQXN5bmNEZWNvbXBpbGF0aW9uLnBuZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/AsyncDecompilation_sml.png" alt="An illustration of successful and failed async decompilation" title="Async Decompilation" width="540" height="554" class="aligncenter size-full wp-image-3251" /></a><br />
<i>Click on the image for an enlarged, more readable version</i></p>
<p>If you&#8217;re interested to know a bit more about the challenge Clive &amp; Ruchika are facing, it boils down to the fact that they&#8217;re trying to update Reflector to have coverage across not one, but 2 new compilers: one for the framework, and a separate (newer) one in Dev11.</p>
<p>  At the moment they&#8217;ve achieved partial coverage, but they&#8217;re working hard to improve that. If the final release of .NET 4.5 is built using a more up-to-date compiler, then we&#8217;ll move as fast as we can to cover that, but we want to make sure you can start experimenting with the latest technology right now.
</p>
<h2 style="padding-top: 5px;">Feedback</h2>
<p>Any and all feedback about the latest build of Reflector is gratefully received! We&#8217;d particularly like to know about any issues you encounter with our async code and Dev11 theming.</p>
<p>In fact, with regards to the async feedback we&#8217;d love to see, let me explain that a little more. As I mentioned earlier, we&#8217;re trying to graciously fail back to .NET 4.0 code when we know we can&#8217;t decompile some async method you&#8217;ve targeted. So, any async code we&#8217;re displaying, we think we&#8217;re handling well.</p>
<p>As such, we&#8217;ve love to hear any feedback about async decompilation that has clearly failed in some way (i.e. where we&#8217;ve tried to generate async code, and it&#8217;s just not right).</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2VhcC8="><strong>Download the latest Early Access build of .NET Reflector</strong></a>, and let us know what you think. If you have any comments about the latest build, just send an email to <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=bWFpbHRvOkVBUEByZWZsZWN0b3IubmV0">EAP@reflector.net</a> – we really appreciate your help.</p>
<p><a href= "http://www.microsoft.com/visualstudio/11/en-us/downloads" target= "_blank"><img src="/blog/wp-content/uploads/2012/05/Get-VS-11-Beta.png"></a></p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3213" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/04/eap-7-6-build-4/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>.NET Framework 4.5 support in .NET Reflector</title>
		<link>http://www.reflector.net/2012/04/net-framework-4-5-support-net-reflector/</link>
		<comments>http://www.reflector.net/2012/04/net-framework-4-5-support-net-reflector/#comments</comments>
		<pubDate>Thu, 12 Apr 2012 15:16:04 +0000</pubDate>
		<dc:creator>Clive</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[EAP]]></category>
		<category><![CDATA[WinRT]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=2836</guid>
		<description><![CDATA[Given that .NET 4.5 is available as part of the beta for Dev11, we have added some new support functionality to .NET Reflector (this is already available in our EAP releases). First, Reflector will now notice if you have .NET 4.5 installed on the machine. As 4.5 is an in-place installation, we notice the presence [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/04/net-framework-4-5-support-net-reflector/' callback='wdgpo_plusone_click'></g:plusone></div> <p>Given that .NET 4.5 is available as part of the beta for  Dev11, we have added some new support functionality to .NET Reflector (this is already available in our EAP releases).</p>
<p>First, Reflector will now notice if you have .NET 4.5 installed on the machine. As 4.5 is an in-place installation, we  notice the presence of certain files to trigger this.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvU2VsZWN0QXNzZW1ibGllcy5wbmc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/SelectAssemblies_sml.jpg" border="0" /></a><br />
<span id="more-2836"></span></p>
<p>This then populates the assembly list with a set of useful  assemblies.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvVXNlZnVsQXNzZW1ibGllcy5qcGc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/UsefulAssemblies_sml.jpg" border="0" /></a></p>
<p style="font-size:10px; font-style:italic">Click for the full screenshot</p>
<p>.NET 4.5 has led to a lot of rearrangement of the assemblies  – there are a lot more assemblies, and using the type forward attributes you  can see what has moved. For example, in <strong>System.Core</strong>, various types (such as  <strong>LockRecursionException</strong>) have been moved elsewhere.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvTG9ja1JlY3Vyc2lvbkV4Y2VwdGlvbi5qcGc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/LockRecursionException_sml.jpg" border="0" /></a></p>
<p style="font-size:10px; font-style:italic">Click for the full screenshot</p>
<p>Using Reflector, we can see that <strong>LockRecursionException</strong> has  a <strong>TypeForwardedAttribute</strong>, and by clicking on the type you can find where it has  moved to. In this case, it has moved to <strong>mscorlib</strong>.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvTG9ja1JlY3Vyc2lvbkV4Y2VwdGlvbl9tc2NvcmxpYi5qcGc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/LockRecursionException_mscorlib_sml.jpg" border="0" /></a></p>
<p style="font-size:10px; font-style:italic">Click for the full screenshot</p>
<p>The other interesting feature added to the language is the  <strong>CallerMemberName</strong>, <strong>CallerFilePath</strong> and <strong>CallerLineNumber </strong>attributes that can be  added to optional arguments to get information about the caller of a given  function. This is implemented, like optional arguments themselves, by baking  extra information into the call site.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvQ2FsbGVyQXR0cmlidXRlcy5qcGc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/CallerAttributes_sml.jpg" border="0" /></a></p>
<p style="font-size:10px; font-style:italic">Click for the full screenshot</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/SimpleApp.jpg" border="0" /></p>
<p>Using Reflector, we can decompile this to see the inlined  arguments at the call sites.</p>
<p>  We have some partial support for the  new C# async/await construct, but we don&rsquo;t yet have Reflector decompiling that perfectly.  However, Reflector is proving to be a useful tool for investigating the new  assemblies that make up the latest release of the .NET framework.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDQvSW52ZXN0aWdhdGluZ05FVEZyZW1ld29yay5qcGc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/04/InvestigatingNETFremework_sml.jpg" border="0" /></a></p>
<p style="font-size:10px; font-style:italic">Click for the full screenshot</p>
<p>If you&#8217;re using <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2VhcC8=" title=\"EAP\"><b>the Early Access release of .NET Reflector to decompile C#5 async constructs</b></a>, it would be great to know what kind of results you&#8217;re getting.</p>
<p><a href= "http://www.microsoft.com/visualstudio/11/en-us/downloads" target= "_blank"><img src="/blog/wp-content/uploads/2012/05/Get-VS-11-Beta.png"></a></p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2836" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/04/net-framework-4-5-support-net-reflector/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Debugging the debugging experience</title>
		<link>http://www.reflector.net/2012/03/debugging-debugging-experience/</link>
		<comments>http://www.reflector.net/2012/03/debugging-debugging-experience/#comments</comments>
		<pubDate>Fri, 30 Mar 2012 11:34:52 +0000</pubDate>
		<dc:creator>Clive</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[experiment]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=2809</guid>
		<description><![CDATA[The CLR is a canny beast that takes liberties with optimising your code using several different mechanisms, which can make debugging retail builds of software an ungainly experience. I&#8217;ve been doing some investigation into how to make this process as similar as possible to “normal&#8217; debugging, which I&#8217;d like to share with you. But first, [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/03/debugging-debugging-experience/' callback='wdgpo_plusone_click'></g:plusone></div> <p>The CLR is a canny beast that takes liberties with optimising your code using several different mechanisms, which can make debugging retail builds of software an ungainly experience. I&#8217;ve been doing some investigation into how to make this process as similar as possible to “normal&#8217; debugging, which I&#8217;d like to share with you. But first, let&#8217;s look at those liberties the CLR is taking.</p>
<p><img class="aligncenter size-full wp-image-2815" title="Debugger science" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/science.jpg" alt="Doing science with the Visual Studio Debugger." width="540" height="154" /></p>
<p><span id="more-2809"></span></p>
<p>First, there&#8217;s the ahead-of-time ngen process. If we&#8217;re not jitting the IL, then there&#8217;s nothing waiting for a quick result, and so we can apply more of the traditional compiler optimisations to generate tighter code. The results are saved as dll files which can be loaded later into the process.</p>
<p>Second, there&#8217;s the JIT compiler itself, which can see if there&#8217;s a debugger attached to the process at the point that the code is jitted. If there <em>is</em> a debugger present, then the JIT compiler can decide to generate code which is more debuggable. In this case, it makes sense that the CLR tries to keep a more accurate mapping between the machine code and the initial IL, which is, in turn, related to the original source code using a pdb file.</p>
<p>Unfortunately, there is a tradeoff between optimisation and one&#8217;s ability to debug the running code. In the old days, the amount of effort a compiler spent improving the generated code was controlled using compiler flags, which in turn were set very differently between retail and debug builds.</p>
<p>Most of the information about the optimisations that the CLR applies is sparsely threaded through independent blogs posts and MSDN documentation. For quite some time I&#8217;ve wanted to sit down and look at the effects of various techniques which people have described as giving the user the best debugging experience. With Reflector VSPro, we really need to know this kind of information – our users typically want to attach to a retail build of a product and debug it, and we&#8217;d like to keep the experience as close as possible to the initial debugging experience you get with a debug build.</p>
<p>With that in mind, this post describes just some of the experiments I did to get confidence with the steps that are needed to keep the debugging experience good. Without a definitive description of the workings of the CLR, experiments are all that we have and, as with all experiments, you can develop a model that doesn&#8217;t accurately reflect what&#8217;s happening. I welcome any feedback.</p>
<p style="padding-left: 20px;"><em>In case you just want the result and don&#8217;t want to read any further, the debugging experience seems to be best if you have the environment variable COMPLUS_ZAPDISABLE set from the time that anything gets jitted, and you also have a suitable ini file placed against one or more assemblies (by suitable I mean “contains suitable control flags to turn off the optimisations&#8217;). I&#8217;d naturally still recommend that you read on, as there are deeper details which are worth knowing!</em></p>
<p>I fully intend to get these settings into Reflector VSPro, so that it&#8217;s the tool rather than the user that sets up the necessary files and environment. At the very least, we intend to have the tool give the user enough information for them to do the work themselves (if Reflector can&#8217;t automate the process). Of course, user intervention is always going to be needed in the case of, for example, an IIS web application which is going to be started before a debugger is attached to it.</p>
<h2>Initial Experiments with Optimization</h2>
<p>For some initial investigation, we&#8217;ll start with the following simple C# console application:</p>
<p><img title="Simple C# application" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image001.png" alt="" width="376" height="291" /></p>
<p>The small method is designed to provoke inlining by the jit compiler, as a way to tell if such optimisations have been disabled. The never-ending loop gives us time to retrospectively attach, while at the same time taking enough processor cycles for the application to show up in process Explorer.</p>
<p>We&#8217;ll compile this code into both debug and release builds. In the case of a debug build we get the following IL</p>
<p><img title="Compiling into a debug build" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image002.png" alt="" width="505" height="590" /></p>
<p>And the following attributes on the Assembly:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvQXNzZW1ibHlfYXR0cmlidXRlcy5qcGc="><img title="Assembly attributes for the debug build" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Assembly_attributes_sml.jpg" alt="" width="540" height="24" border="0" /></a></p>
<p>&nbsp;</p>
<p>(click on the image above for to enlarge)</p>
<p>The NOPs are present to allow a better mapping, via the pdb file, back to the original source code. I believe it is this long <strong>DebuggableAttribute</strong> that turns off some of the optimisations (as we&#8217;ll soon see).</p>
<p>In release build, we get the following code:</p>
<p><img title="Compiling into a release build" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image005.png" alt="" width="491" height="424" /></p>
<p>And the following attributes</p>
<p><img title="Assembly attributes for a release build" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image006.png" alt="" width="540" height="31" /></p>
<p>We first run the release version, letting it get into the code which does the printing so that we can be sure the methods are jitted. We can then attach using <strong>windbg</strong> and look at the loaded modules.</p>
<p>I believe the CLR currently doesn&#8217;t re-jit methods – this has been added as a feature in .NET 4.5 so that an attached profiler can demand the re-jit of methods. However, the CLR doesn&#8217;t <em>yet</em> do the kinds of work that a Java HotSpot compiler does using on-stack replacement and adaptive compilation to specialise the code, depending on dynamic call patterns. What it <em>does</em> do is optimised interface dispatch using dynamically generated stubs after a slow path has been executed a number of times, but that doesn&#8217;t affect our example here.</p>
<p>In Windbg, we see the following modules have been loaded:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvV2luREJHX21vZHVsZXMuanBn"><img title="Modules found by windbg in the release build" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/WinDBG_modules_sml.jpg" alt="" width="540" height="76" border="0" /></a></p>
<p>The <strong>mscorlib.ni.dll</strong> is the result of the ngen processing of the assembly.</p>
<p>If we do the same thing with the debug version, letting it run and then attaching, we see that the following modules were loaded:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvRGVidWdnZXJfY2xpcF9pbWFnZTAxMC5qcGc="><img title="Modules found by windbg in the debug build" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image010_sml.jpg" alt="" width="540" height="74" border="0" /></a></p>
<p>We see that the debug version of our compiled method doesn&#8217;t load the ngen version of mscorlib. I&#8217;ll attempt to show below that this has led to a better debugging experience.</p>
<h2>Better Debugging</h2>
<p>In the release case, we can attach with Visual Studio after the warm-up period described above. Using the disassembler pane, we see that the code for our method looks like this:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvQmV0dGVyX2RlYnVnZ2luZzEuanBn"><img title="" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Better_debugging1_sml.jpg" alt="" width="540" height="314" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>We can see that the small method which calls <strong>WriteLine</strong> has been inlined, and that the stack trace doesn&#8217;t show the call into <strong>Console.WriteLine</strong>.</p>
<p>If we now run the Debug version, we see that there is no inlining happening, and mscorlib is less heavily optimised, so the stack trace is more accurate. This lack of optimisation is essential for being able to accurately debug with a minimum of hassle.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvQmV0dGVyX2RlYnVnZ2luZzIuanBn"><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Better_debugging2_sml.jpg" alt="" width="540" height="314" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>The big question is this: <strong>can we take the Release build and get the same debugging experience?</strong></p>
<p>First, we can try setting <strong>COMPLUS_ZAPDISABLE</strong>, which prevents the system loading ngen&#8217;ed assemblies. This needs to be set <em>before</em> the point that the loading is triggered by the jit.</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image016.jpg" alt="" width="540" height="24" /></p>
<p>This leads to the following set of loaded modules, which I got by letting the release build run and then attaching windbg:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvRGVidWdnZXJfY2xpcF9pbWFnZTAxOC5qcGc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image018_sml.jpg" alt="" width="540" height="76" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>And if we attach from Visual Studio, we see the following:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvQmV0dGVyX2RlYnVnZ2luZzMuanBn"><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Better_debugging3_sml.jpg" alt="" width="540" height="314" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>We can see that the ngen&#8217;ed image hasn&#8217;t been loaded, but inlining has still taken place.</p>
<p>The second trick is to set up an ini file to control the optimization for jitted code. In this case, we&#8217;ll be setting it against the top level application – it has the same name as the file but with the exe or dll extension replaced with ini. Into it, we can put some configuration options; one saying that we&#8217;d like to track the machine-code-to-IL relationship, and another to turn off optimisations.</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image022.jpg" alt="" width="540" height="174" /></p>
<p>Adding this .ini file has a dramatic effect on the debugging experience.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvQmV0dGVyX2RlYnVnZ2luZzQuanBn"><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Better_debugging4_sml.jpg" alt="" width="540" height="314" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>Notice that no inlining has happened inside the user code, and we now get a faithful stacktrace for mscorlib.</p>
<h2>Back to the lab!</h2>
<p>As a further experiment, we can unset the COMPLUS_ZAPDISABLE, which leads to the ngen&#8217;ed mscorlib being reloaded, though the inlining has still been turned off:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvaW5saW5pbmdfdHVybmVkX29mZi5qcGc="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/inlining_turned_off_sml.jpg" alt="" width="540" height="89" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>If we take a small example project, the COMPLUS_ZAPDISABLE noticeably changes the behaviour so that there are many more places where we can effectively set the next statement in the code. For a simple project using the in-built WebDev webserver, if the devenv.exe that launches it was launched in a COMPLUS_ZAPDISABLE environment, then stepping into something like mscorlib is a lot better. Unfortunately, the experience doesn&#8217;t become “full&#8217; until you put an .ini file next to the mscorlib to ensure proper stepping and ‘move next statement&#8217; behaviour. Hence we seem to need both the environment variable <em>and</em> the ini file to get the best results.</p>
<p>We should also point out that, in the above experiments, we have been improving the behaviour when we attach the debugger after the application has been running for a while, and so jitting has already taken place. If you are debugging into a project by launching it from Visual Studio, then the fact that the debugger is attached when the jitting happens also improves the debugging experience. The extra complication in <em>that</em> scenario is that there is a hosting process which is used by Visual Studio to provide debugging – turning this off can also be useful.</p>
<p>I was also interested to see how to improve the experience for debugging a web application running under IIS, so I wrote a simple web application with a simple button on the main page, and the following code behind. <strong>Console.WriteLine</strong> is a common theme in these examples because it gives us an easy way to get into <strong>mscorlib.dll</strong>, and the <strong>WriteLine</strong> method makes a call to another method, so we can see if this call gets inlined (allowing us to see if optimisation is happening).</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/Debugger_clip_image027.png" alt="" width="423" height="120" /></p>
<p>The loop is handy, because we can easily identify the <strong>w3wp.exe</strong> process that is hosting the application by seeing which one starts consuming CPU after the button is hit in the ASP.NET application.</p>
<h2>A little help from Microsoft</h2>
<p>I was a little worried about tweaking the setting for the w3wp.exe process, which is used by IIS to host the CLR running the web application. However, while looking around, I came across a script that Microsoft provides to aid with the profiling of .NET Web Applications:</p>
<p>c:/Program Files (x86)/Microsoft Visual Studio 8/Team Tools/Performance Tools/VSPerfCLREnv.cmd</p>
<p>This also sets various environment variables to control loading of the CLR Profiler around a re-launch of the application. The CLR loads a profiler dll as a COM component, if directed to do so at startup time by environment variable settings.</p>
<p>The script also controls the environment variables for services using the following part of the registry.</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvcmVnaXN0cnkuanBn"><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/registry_sml.jpg" alt="" width="540" height="196" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>With this in mind, I went into the registry, added a setting of COMPLUS_ZAPDISABLE to 1, and then killed the w3wp.exe process, and the svchost process that was its parent. I did this using the process explorer tool from <strong><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5zeXNpbnRlcm5hbHMuY29tLw==">SysInternals</a></strong>, which allows you to easily see the relationship between running processes, and which also allows you to see the environment variable settings for a given process. This tool makes it easy to check that the changes have taken effect.</p>
<p>When I hit the web page again, w3wp.exe is re-launched and process explorer shows that the setting has taken effect:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvdzN3cF9wcm9wZXJ0aWVzLmpwZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/w3wp_properties_sml.jpg" alt="" width="540" height="301" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>Attaching windbg to the w3wp shows that there is no ngen loading for the IIS process:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvV2luREJHX2R1bXAxLmpwZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/WinDBG_dump1_sml.jpg" alt="" width="540" height="324" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>Using Process Monitor, you can also see the process probing for .ini files next to all of the assemblies that it jits. Going into the GAC and placing a suitable .ini file against the relevant assembly, in this case mscorlib.dll, allowed me to later attach with Visual Studio and get a good debugging experience – stepping was accurate, variable values were always available, and ‘set next statement&#8217; worked effectively.</p>
<p>Whereas in the case of the simple windows forms application, placing an .ini file against the top level assembly seemed to affect the behaviour of the jit for the loaded modules, in the case of the w3wp.exe, the only .ini files that are probed are the ones that are next to the loaded assemblies (included those that are dynamically generated by ASP.NET)</p>
<p>The final question is whether we need to set the debug property in the <strong>Web.Config</strong>:</p>
<p><span style="color: blue;">&lt;</span><span style="color: #900;">system.web</span><span style="color: blue;">&gt;</span></p>
<p><span style="color: blue;">&lt;</span><span style="color: #900;">compilation</span> <span style="color: red;">debug</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">true</span>&#8221; <span style="color: red;">targetFramework</span><span style="color: blue;">=&#8221;4.0&#8243; /&gt;</span></p>
<p>And I don&#8217;t yet have a particularly good answer for that, though I imagine it affects at least the setting of the compiler when ASP.NET generates the application assemblies. Setting it and then attaching windbg to the resulting w3wp.exe shows that the ngen images <em>are</em> being loaded:</p>
<p><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvV2luREJHX2R1bXAyLmpwZw=="><img src="http://www.reflector.net/blog/wp-content/uploads/2012/03/WinDBG_dump2_sml.jpg" alt="" width="540" height="305" border="0" /></a></p>
<p>(click on the image above for to enlarge)</p>
<p>&#8230; So it certainly doesn&#8217;t turn off all optimization. I&#8217;ll need to do more work to find out exactly what it <em>does</em> do.</p>
<h2>The Takeaway</h2>
<p>In summary, if you want to get a better debug experience for debugging retail builds, you need to make sure that COMPLUS_ZAPDISABLE is set, and probably place .ini files in the right place (which is most likely next to all of the assemblies your process is going to load). This needs to be done in advance, or at least before the assembly is loaded in order to get the best experience.</p>
<p>Hopefully you&#8217;ll be able to use this method right away, and we&#8217;re working on getting as much of this automated in .NET Reflector as possible. And as I said at the start, this is all rather experimental, so all feedback is welcome.</p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2809" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/03/debugging-debugging-experience/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>EAP 7.6 Build 2, Take 2</title>
		<link>http://www.reflector.net/2012/03/eap-7-6-build-2-2/</link>
		<comments>http://www.reflector.net/2012/03/eap-7-6-build-2-2/#comments</comments>
		<pubDate>Fri, 23 Mar 2012 17:39:01 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=2759</guid>
		<description><![CDATA[We released a patch for EAP build 2 this afternoon, and we recommend you grab it. Due to an entertaining quirk, the async functionality Clive was working on didn&#8217;t actually play nicely on our users machines. Luckily, Clive very quickly figured out why, and today&#8217;s build fixes the issue. So, with the latest release, you&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/03/eap-7-6-build-2-2/' callback='wdgpo_plusone_click'></g:plusone></div> <p>We released a patch for EAP build 2 this afternoon, and <a title=\"EAP\" href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2VhcC8=">we recommend you grab it</a>.</p>
<p>Due to an entertaining quirk, the async functionality Clive was working on didn&#8217;t actually play nicely on our users machines. Luckily, Clive very quickly figured out why, and today&#8217;s build fixes the issue. So, with the latest release, you&#8217;ll be able to see the very early async support we&#8217;ve been working on (please bear in mind that we&#8217;re only talking about a small subset of async functionality at this stage).</p>
<p>As an added bonus, Nigel has also been busy, so you&#8217;ll see some small enhancements to the Dev11 theming as well.</p>
<p>Take the new build for a spin, please <a title=\".NET Reflector EAP Feedback\" href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cHM6Ly9nZXRzYXRpc2ZhY3Rpb24uY29tL2RvdG5ldHJlZmxlY3Rvcg==">let us know what you think</a>, and have a great weekend</p>
<p>Cheers,</p>
<p>Chris</p>
<p><a href= "http://www.microsoft.com/visualstudio/11/en-us/downloads" target= "_blank"><img src="/blog/wp-content/uploads/2012/05/Get-VS-11-Beta.png"></a></p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2759" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/03/eap-7-6-build-2-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EAP 7.6 Build 2</title>
		<link>http://www.reflector.net/2012/03/eap-7-6-build-2/</link>
		<comments>http://www.reflector.net/2012/03/eap-7-6-build-2/#comments</comments>
		<pubDate>Tue, 20 Mar 2012 10:32:46 +0000</pubDate>
		<dc:creator>Nigel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">https://www.reflector.net/?p=2713</guid>
		<description><![CDATA[Visual Studio Dev 11 looks…. different.  If you’ve not seen it, then you’re in for a surprise (you can download the latest VS11 Beta from a link at the bottom of this post). It’s gone monochrome, with no colour in most of the icons, and colour is only used when you really need to look [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/03/eap-7-6-build-2/' callback='wdgpo_plusone_click'></g:plusone></div> <p>Visual Studio Dev 11 looks…. different.  If you’ve not seen it, then you’re in for a surprise (you can download the latest VS11 Beta from a link at the bottom of this post). It’s gone monochrome, with no colour in most of the icons, and colour is only used when you <em>really</em> need to look at something (apparently). The other new addition to the look is the idea of Themes. Dev 11 ships with a light theme and a dark theme (Must. Resist. Force. Comparisons.), which basically amount to light grey or dark grey.</p>
<p><img class="aligncenter size-full wp-image-2734" title="Dev11 Themed Object Browser" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/ThemedROB.jpg" alt="The current theming of the .NET Reflector Object Browser in Dev11" width="540" height="241" /></p>
<p><span id="more-2713"></span></p>
<p>When I first started coding, it was always light text on a dark background (my amstrad CPC had a monochrome green screen &#8211; we couldn’t afford the colour version), and later my xemacs editor was set to roughly the same. So when I first came to visual studio, I hated the sea of white burning my eyes; and now I’m not sure if I want to go back. On a more immediately pressing note, as we have the Reflector object browser inside visual studio, it stuck out like a sore thumb with its white background, so I was tasked with investigating how to hook into the new Dev 11 themes, so it doesn’t look so out of place.</p>
<p>Dev 11, like 2010 before it, uses WPF. At least, if you’re writing an extension and add a new tool window, you’re invited to fill it with some XAML. In theory then, there are ways to just pick up the default theme colours (and ways to create new ones if needed).</p>
<p>However, most of the reflector UI was written some time ago in WinForms, and whilst we’d like to replace it with glorious WPF, that isn’t on the cards for this version.  Luckily, the Dev 11 SDK adds an API call to ask about various theme colours, and a hook to know when it’s changed.</p>
<p>So in this EAP, the Reflector object browser now at least changes its basic text and background colour to try and blend in. There is more to do here, but I had other investigations to look at before finishing that work (around the upgrade/update process, which in parts, quite frankly, currently sucks a bit).</p>
<p>Clive has been much more productive – he’s added basic C# 5 async support (I can’t wait to actually be able to use that feature, it will make certain things so much easier).</p>
<p>So head over to <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2VhcC8=">the EAP page</a> and take a look, and have a play with some C#5 features.</p>
<p>Nigel</p>
<p><a href= "http://www.microsoft.com/visualstudio/11/en-us/downloads" target= "_blank"><img src="/blog/wp-content/uploads/2012/05/Get-VS-11-Beta.png"></a></p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2713" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/03/eap-7-6-build-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grab a free copy of “Under the hood of .NET Memory Management”</title>
		<link>http://www.reflector.net/2012/03/grab-free-copy-%e2%80%9cunder-hood-net-memory-management%e2%80%9d/</link>
		<comments>http://www.reflector.net/2012/03/grab-free-copy-%e2%80%9cunder-hood-net-memory-management%e2%80%9d/#comments</comments>
		<pubDate>Tue, 13 Mar 2012 17:49:34 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[ebook]]></category>
		<category><![CDATA[memory]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=2701</guid>
		<description><![CDATA[If you’ve ever wondered about .NET memory management, or had to get into the guts of your code to track down a memory leak, or wanted to make sure that your code performs as fast as possible, and with a small memory footprint, then I’ve got a book you should read. At the risk of [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/03/grab-free-copy-%e2%80%9cunder-hood-net-memory-management%e2%80%9d/' callback='wdgpo_plusone_click'></g:plusone></div> <p>If you’ve ever wondered about .NET memory management, or had to get into the guts of your code to track down a memory leak, or wanted to make sure that your code performs as fast as possible, and with a small memory footprint, then I’ve got a book you should read. At the risk of being biased, it’s a book which I edited, and took from concept to print.</p>
<p><img class="aligncenter size-full wp-image-2704" title="Under The Hood of .NET Memory Management" src="http://www.reflector.net/blog/wp-content/uploads/2012/03/UnderTheHood.jpg" alt="'Under The Hood of .NET Memory Management', by Chris Farrell and Nick Harrison" width="540" height="253" /></p>
<p>More to the point, it’s an eBook which is currently free to download: <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWQtZ2F0ZS5jb20vcHJvZHVjdHMvZG90bmV0LWRldmVsb3BtZW50L2FudHMtbWVtb3J5LXByb2ZpbGVyL2xlYXJuaW5nLW1lbW9yeS1tYW5hZ2VtZW50L21lbW9yeS1tYW5hZ2VtZW50LWZ1bmRhbWVudGFscz91dG1fc291cmNlPXJlZmxlY3RvciZhbXA7dXRtX21lZGl1bT1ibG9nJmFtcDt1dG1fY29udGVudD1yaWNreWxlZWtzNSZhbXA7dXRtX2NhbXBhaWduPWFudHNtZW1vcnlwcm9maWxlcg==">“Under the hood of .NET memory Management” by Chris Farrell and Nick Harrison</a>. The book normally retails on Amazon for about $22, but you can download it for free (split into two parts) from the Red Gate website.<br />
<span id="more-2701"></span></p>
<p>The book is part of an on-going project by Red Gate to help .NET developers learn more about .NET memory management (and thus write better code or debug issues faster). The front-man for this is <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cHM6Ly90d2l0dGVyLmNvbS8jIS9yaWNreWxlZWtzXw==">Ricky Leeks</a>, who (with a little help) regularly sources and publishes substantial .NET content.</p>
<p><strong>If you want to know what’s on offer, here’s a quick summary:</strong></p>
<p>Chris Farrell opens up with some great chapters laying out the .NET memory management model, and closes the book with some deeper dives into the Windows memory model and advanced .NET memory considerations like parallelism and 64-bit vs 32-bit. In the middle, Nick Harrison (<a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5zaW1wbGUtdGFsay5jb20vZG90bmV0Ly5uZXQtdG9vbHMvcmV2aXNpdGluZy1ob3N0aW5nLXJlZmxlY3Rvci8=">who is a regular author over on Simple-Talk</a>), walks through .NET memory troubleshooting and some handy platform-specific tips covering everything from ASP.NET to WPF.</p>
<p>“Under the hood of .NET memory management” is pretty comprehensive, and I’d strongly recommend it to anyone who wants to take their debugging and development up a notch (and not just because I worked on it). <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWQtZ2F0ZS5jb20vcHJvZHVjdHMvZG90bmV0LWRldmVsb3BtZW50L2FudHMtbWVtb3J5LXByb2ZpbGVyL2xlYXJuaW5nLW1lbW9yeS1tYW5hZ2VtZW50L21lbW9yeS1tYW5hZ2VtZW50LWZ1bmRhbWVudGFscz91dG1fc291cmNlPXJlZmxlY3RvciZhbXA7dXRtX21lZGl1bT1ibG9nJmFtcDt1dG1fY29udGVudD1yaWNreWxlZWtzNSZhbXA7dXRtX2NhbXBhaWduPWFudHNtZW1vcnlwcm9maWxlcg==">Grab your free</a> copy, and check out Ricky Leeks’ top tips (which are regularly updated, and well worth a read).</p>
<hr />
<p><b>EDIT: <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWQtZ2F0ZS5jb20vcHJvZHVjdHMvZG90bmV0LWRldmVsb3BtZW50L2FudHMtbWVtb3J5LXByb2ZpbGVyL2xlYXJuaW5nLW1lbW9yeS1tYW5hZ2VtZW50L21lbW9yeS1tYW5hZ2VtZW50LWdvdGNoYXM/dXRtX3NvdXJjZT1yZWZsZWN0b3ImIzAzODt1dG1fbWVkaXVtPWJsb2cmIzAzODt1dG1fY29udGVudD1yaWNreWxlZWtzNiYjMDM4O3V0bV9jYW1wYWlnbj1hbnRzbWVtb3J5cHJvZmlsZXI=" title=\"Under the Hood of .NET Memory Management\">Part 2 of the eBook is now available</a>, along with a link back to part 1 if you missed it.</b></p>
<hr />
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2701" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/03/grab-free-copy-%e2%80%9cunder-hood-net-memory-management%e2%80%9d/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>A new EAP release: Dev11, .NET 4.5, and C# 5</title>
		<link>http://www.reflector.net/2012/03/7-6-first-eap/</link>
		<comments>http://www.reflector.net/2012/03/7-6-first-eap/#comments</comments>
		<pubDate>Fri, 09 Mar 2012 10:06:21 +0000</pubDate>
		<dc:creator>RogerHart</dc:creator>
				<category><![CDATA[Beta]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[EAP]]></category>
		<category><![CDATA[Future]]></category>
		<category><![CDATA[New Release]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=2678</guid>
		<description><![CDATA[We’ve been a bit quiet on the EAP front recently, and there’s a reason for that. The rest of the team and I feel like we’ve spent the last fortnight locked in a meeting room. In hindsight, that’s substantially because we have. All I can see when I close my eyes is post-it notes, but [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/03/7-6-first-eap/' callback='wdgpo_plusone_click'></g:plusone></div> <p>We’ve been a bit quiet on the EAP front recently, and there’s a reason for that. The rest of the team and I feel like we’ve spent the last fortnight locked in a meeting room. In hindsight, that’s substantially because we have. All I can see when I close my eyes is post-it notes, but we’re getting a lot closer to scoping out version 8 of Reflector.</p>
<p>V8 is all kinds of exciting, but still very much at the on-paper stage. But somehow, in the midst of all the planning, and sketching, and brainstorming, and well-intentioned bickering,  Clive, Nigel, Ruchika, and Nick have shipped a new EAP.</p>
<p>The <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2VhcC8=">version 7.6 EAP</a> is the first slice of our support for Visual Studio Dev 11, .NET 4.5, and C# 5</p>
<p>Reflector’s Visual Studio integration is now working in Dev11, so you can decompile code and start to debug it within the new VS beta. You can explore the changes in the .NET 4.5 framework too, and Clive has a blog post coming about this shortly.</p>
<p>Because it’s our first EAP, it’s not all up and running yet. For example, we aren’t currently decompiling the new C# async/await construct,  but we’ll be fleshing out the C# 5 support in the coming releases.</p>
<p>To get an idea of what’s planned for Reflector 7.6, <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2VhcC8=">take a look at the EAP page</a></p>
<div class="grey">
<div class="button download floatleft"><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3Nob3AucmVmbGVjdG9yLm5ldC9kb3dubG9hZC9sYXRlc3QvZWFw" title=\"Download the latest Early Access Build of .NET Reflector v7.6\" onclick=\"_gaq.push(['_trackEvent', 'eap', 'download', 'download the eap']);\"> <span class="majortext">Download EA build 7<br /> <span class="minortext">Expires 29th March</span></span></a> </div>
<p><br style="clear:both;">
</div>
<p><a href= "http://www.microsoft.com/visualstudio/11/en-us/downloads" target= "_blank"><img src="/blog/wp-content/uploads/2012/05/Get-VS-11-Beta.png"></a></p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2678" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/03/7-6-first-eap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Assembly Diff Algorithms &#8211; it&#8217;s all in the details</title>
		<link>http://www.reflector.net/2012/03/assembly-diff-algorithms/</link>
		<comments>http://www.reflector.net/2012/03/assembly-diff-algorithms/#comments</comments>
		<pubDate>Thu, 08 Mar 2012 16:13:59 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[extensions]]></category>
		<category><![CDATA[add-ins]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[diff]]></category>

		<guid isPermaLink="false">http://www.reflector.net/?p=2612</guid>
		<description><![CDATA[A long, long time ago in a galaxy far, far away, Sean Hederman wrote an add-in for Reflector called Reflector.Diff. It was originally created to help him dive into code differences between Framework versions, but he figured it could also work nicely for people who wanted to diff their own assemblies. We got in touch [...]]]></description>
			<content:encoded><![CDATA[<div class='wdgpo wdgpo_standard_count'><g:plusone size='standard' count='true' href='http://www.reflector.net/2012/03/assembly-diff-algorithms/' callback='wdgpo_plusone_click'></g:plusone></div> <p>A long, long time ago in a galaxy far, far away, Sean Hederman wrote an add-in for Reflector called <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5jb2RpbmdzYW5pdHkuY29tL2RpZmYuaHRt" target=\"_blank\">Reflector.Diff</a>. It was originally created to help him dive into code differences between Framework versions, but he figured it could also work nicely for people who wanted to diff their <em>own</em> assemblies.</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/02/Diff.png" alt="Screenshot of the old Reflector.Diff" /></p>
<p>We got in touch with Sean, and he gave us some more details into how he developed the Algorithm and UI in Reflector.Diff 2<br />
<span id="more-2612"></span></p>
<hr />
<p>To perform the diffs, I used an excellent library by Michael Potter which described how to create a diff engine. I modified it (with his permission), and hooked it into .NET Reflector (with <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5sdXR6cm9lZGVyLmNvbS8=" target=\"_blank\">Lutz Roeder’s</a> very patient help); suffice to say, this compact little tool became pretty popular. I have no idea <strong><em>how</em></strong> popular because I wasn’t tracking downloads or anything like that, but I certainly got a lot of link love for it (although to my now-defunct dotnet.org.za blog – lesson learned: don’t put your work under the control of other people).</p>
<p>Anyway, bygones.</p>
<p>After a while, I decided it was time for a revamp of the project. I wanted Diff to work on the newest and coolest version of Reflector, I wanted to get the UI updated, and I wanted to make it fast. Damn fast.</p>
<p>This is a story, not about me, but about some very clever people and their very clever algorithms.</p>
<h2 style="padding-top: 5px;">In the beginning was the algorithm</h2>
<p>All differencing algorithms, given 2 inputs, attempt to try and find a set of modifications which will turn Input A into Input B.</p>
<p><img src="http://www.reflector.net/blog/wp-content/uploads/2012/02/Diff_process.png" alt="The flow from Input A through the modifications to Input B" /></p>
<p>Counter-intuitively, most difference algorithms focus not so much on finding a set of differences as finding the <em>similarities</em> between the two inputs; this is known as the <strong><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9Mb25nZXN0X2NvbW1vbl9zdWJzZXF1ZW5jZV9wcm9ibGVt" target=\"_blank\">Longest Common Subsequence problem</a></strong>. Think about it: if you find the commonalities; then all the bits that <em>aren’t</em> common are the changes. If the change is found in the source, but not in the destination, it’s a deletion, and if vice versa, it’s an insert.</p>
<p>As I mentioned, the algorithm I found for Reflector.Diff version 1 was written by <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5jb2RlcHJvamVjdC5jb20vS0IvcmVjaXBlcy9kaWZmZW5naW5lLmFzcHg=" target=\"_blank\">Michael Potter</a>, and he kindly allowed me to use it to build my original differencing engine. His algorithm was, in turn, based on one by <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5jb2RlcHJvamVjdC5jb20vS0IvcmVjaXBlcy9jX19kaWZmX2FsZ29yaXRobS5hc3B4" target=\"_blank\">Aprenot</a>, which was all fine, considering my original intended purpose for the tool, but there’s always room for improvement.</p>
<p>More recently, I wrote a little test harness running diffs against a large project and checking the performance. For most purposes, the original version of Reflector.Diff was good enough for my needs; but I noticed that sluggishness would start to creep in for large diffs (such as looking at the <strong>System</strong> namespace in mscorlib). With a more detailed analysis, I found that it became slower when given larger texts and more changes <em>within</em> those texts, as would be expected. It also seemed to fall off a cliff at about 4,000 lines (but admittedly, I only tested up to 5,000 lines).</p>
<h2 style="padding-top: 5px;">Speed is everything</h2>
<p>I did a little digging around and found a <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5zcHJpbmdlcmxpbmsuY29tL2NvbnRlbnQvbDMyNjg1eHE2NTIyMzg4Mi8=" target=\"_blank\">well-known algorithm</a> by <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9FdWdlbmVfTXllcnM=" target=\"_blank\">Eugene Myers</a>, as well as some <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL25laWwuZnJhc2VyLm5hbWUvd3JpdGluZy9kaWZmLw==" target=\"_blank\">little-known optimizations</a> to this algorithm (designed by <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL25laWwuZnJhc2VyLm5hbWUv" target=\"_blank\">Neil Fraser</a>) that help speed it up significantly in the most common scenarios. The new engine looked good, so I slapped it into Reflector.Diff and reran my tests. The question is, did it help?</p>
<p>In 42% of cases, my new algorithm was actually slower by an average of 622μs per file. Not ideal, but not too bad, either. And in the 58% of cases when it was faster? In those cases, it averaged 64ms faster.</p>
<p>To put that in perspective,  in the58% of cases when it was faster, it was <em>100 times faster</em> than the old algorithm. Overall (i.e. averaging across all the test scenarios), the new algorithm worked out to be about 9 times faster. So, for a set of 100 files totalling 140,000 lines, it compared them in 0.76 seconds, as opposed to the 7 seconds it would take the original algorithm. I excluded file access times from these calculations, so the figures I’m bandying about were for the straight line comparison of sets of two large strings, held in memory.</p>
<p>Naturally, I’m pretty happy with the improvement, especially considering the scare I originally had while working out the performance benchmarks:</p>
<p>&lt;<em>flashback</em>&gt;</p>
<p>…I did a set of trial runs once I’d initially worked out how to build my performance improvements, and the new algorithm was vastly <em>slower</em>. <em>Hundreds</em> of times slower, in some cases.</p>
<p>I broke out my trusty <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWQtZ2F0ZS5jb20vcHJvZHVjdHMvZG90bmV0LWRldmVsb3BtZW50L2FudHMtcGVyZm9ybWFuY2UtcHJvZmlsZXIvP3V0bV9zb3VyY2U9cmVmYmxvZyYjMDM4O3V0bV9tZWRpdW09YmxvZyYjMDM4O3V0bV9jb250ZW50PWFwcDcmIzAzODt1dG1fY2FtcGFpZ249YW50c3BlcmZvcm1hbmNlcHJvZmlsZXI=" target=\"_blank\">ANTS Performance Profiler</a>, compared the two algorithms, and found that, for all of its theoretical improvements, my new design was doing hugely more work. A little spelunking through the call stack and I came to the reason why: the old algorithm was differencing the files on a line-by-line basis, and the new one was doing it <em>character-by-character</em>. Once I changed the new one to work line-by-line, I started getting <em>much</em> better figures. I have no idea how long I’d have flailed around if it hadn’t been for that “oh crap” epiphany looking at line hit counts in ANTS.</p>
<div id="attachment_2615" class="wp-caption aligncenter" style="width: 550px"><a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5yZWZsZWN0b3IubmV0L2Jsb2cvd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDIvRGlmZl9saW5lLnBuZw=="><img class="size-full wp-image-2615" title="Diff_Algorithm_Performance_sml" src="http://www.reflector.net/blog/wp-content/uploads/2012/02/Diff_line_sml.png" alt="The Diff algorithm taking a huge performance hit." width="540" height="20" /></a><p class="wp-caption-text">560,000 iterations is probably not a good sign for finding differences in a single file, even if it is a couple thousand lines.</p></div>
<p>&lt;<em>/flashback</em>&gt;</p>
<h2 style="padding-top: 5px;">Speed isn&#8217;t everything</h2>
<p>On the other hand, we also need to consider the tried-and-tested technique of faking performance, which I&#8217;ve <a href="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2dzLnBhbGFudGlyLmNvLnphL2NvZGluZ3Nhbml0eS9hcmNoaXZlLzIwMTAvMDgvMjYvZmFraW5nLWl0LmFzcHg=" target=\"_blank\">written this before</a>. There are two psychological considerations to bear in mind.</p>
<p>Firstly, when people see your app stop responding (hanging), they get a negative impression of its performance. Secondly, people perceive operations accompanied by progress bars as being faster than the <em>exact same</em> operation without a progress bar.</p>
<p>However, I didn&#8217;t want to just pop up a progress bar willy nilly whenever Reflector.Diff was doing anything at all – that would be a User Experience mess, and I wanted to use my new-found knowledge wisely. So, I created a <strong>BackgroundWorker</strong> subclass to handle the Differencing operation for me, and designed it to pop up a screen with a progress bar, but <em>only</em> if the operation has taken longer than one second.</p>
<p>This way, we get the best of all worlds; a responsive UI, coupled with a progress bar if it starts taking too long. The progress bar itself? Eye candy, nothing more &#8211; there for the sole purpose of implying that the application is working faster than it actually is. Or rather, of giving the user confidence that the application is working, not hanging.</p>
<h2 style="padding-top: 5px;">The takeaway</h2>
<p>Diff is designed to do one thing, and one thing well: compare two assemblies and display the differences between them. With that in mind, the work I’ve done to enhance Reflector.Diff is to make it easier and faster to use – take it for a spin, and I hope it works well for you.</p>
 <img src="http://www.reflector.net/blog/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2612" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.reflector.net/2012/03/assembly-diff-algorithms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

