<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://msmvps.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Peter Ritchie's MVP Blog : DevCenterPost</title><link>http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx</link><description>Tags: DevCenterPost</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>IDisposable and Class Hierarchies</title><link>http://msmvps.com/blogs/peterritchie/archive/2013/01/21/idisposable-and-class-hierarchies.aspx</link><pubDate>Mon, 21 Jan 2013 17:11:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1822950</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1822950</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2013/01/21/idisposable-and-class-hierarchies.aspx#comments</comments><description>&lt;p&gt;In my &lt;a href="http://msmvps.com/blogs/peterritchie/archive/2013/01/20/the-dispose-pattern-as-an-anti-pattern.aspx"&gt;previous post&lt;/a&gt;, I showed how the Dispose Pattern is effectively obsolete. But, there&amp;rsquo;s one area that I didn&amp;rsquo;t really cover.&amp;nbsp; What do you do when you want to create a class that implements &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable&lt;/span&gt;, doesn&amp;rsquo;t implement the Dispose Pattern, &lt;strong&gt;and&lt;/strong&gt; will be derived from classes that will also implement disposal?&lt;/p&gt;
&lt;p&gt;The Dispose Pattern covered this by coincidence.&amp;nbsp; Since something that derives from a class that implements the Dispose Pattern simply overrides the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(bool)&lt;/span&gt; method, you effectively have a way to chain disposal from the sub to the base. There&amp;rsquo;s a lot of unrelated chaff that comes along with Dispose Pattern if that&amp;rsquo;s all you need.&amp;nbsp; What if you want to design a base class that implements &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable&lt;/span&gt; and support sub classes that might want to dispose of managed resources?&amp;nbsp; Well, you&amp;rsquo;re not screwed.&lt;/p&gt;
&lt;p&gt;You can simply make your &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable.Dispose&lt;/span&gt; method virtual and a sub can override it before calling the base.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="font-size:12pt;"&gt;	&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Base&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; : &lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt; managedResource;
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/span&gt;
&lt;span style="color:#000000;"&gt;		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;virtual&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt; Dispose()
		{
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;(managedResource != &lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;null&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;) managedResource.Dispose();
		}
	}
 
	&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Sub&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; : &lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Base&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt; managedResource;
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;override&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt; Dispose()
		{
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; (managedResource != &lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;null&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="color:#000000;"&gt;) managedResource.Dispose();
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;base&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;.Dispose();
		}
	}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;If you don&amp;rsquo;t implement a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;virtual Dispose&lt;/span&gt; and you don&amp;rsquo;t implement the Dispose Pattern, you should&lt;strong&gt; use the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;sealed&lt;/span&gt; modifier on your class&lt;/strong&gt; because you&amp;rsquo;ve effectively made it impossible for base class to dispose of both their resources and the base&amp;rsquo;s resources in all circumstances.&amp;nbsp; In the case of a variable declared as the base class type that holds an instance of a subclassed type (e.g. &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Base base = new Sub()&lt;/span&gt;) only the base &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt; will get invoked (all other cases, the sub &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt; will get called).&lt;/p&gt;
&lt;h2&gt;Caveat&lt;/h2&gt;
&lt;p&gt;If you do have a base class that implements &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable&lt;/span&gt; and doesn&amp;rsquo;t implement a virtual &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt; or implement the Dispose Pattern (e.g. outside of your control) then you&amp;rsquo;re basically screwed in terms of inheritance.&amp;nbsp; In this case, I would prefer composition over inheritance.&amp;nbsp; The type that would have been the base simply becomes a member of the new class and is treated just like any other disposable member (dealt with in the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable.Dispose&lt;/span&gt; implementation).&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="font-size:12pt;"&gt;	&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Base&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; : &lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/span&gt;
&lt;span style="color:#000000;"&gt;		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt; Dispose()
		{
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;		}
	}
 
	&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Sub&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; : &lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Base&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt; theBase;
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="color:#000000;"&gt; 
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; Dispose()
		{
			theBase.Dispose();
		}
	}
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;This, of course, means you need to either mirror the interface that the previously-base-class provides, or provide a sub-set of wrapped functionality so the composed object can be used in the same ways it could have been had it been a base class.&lt;/p&gt;
&lt;p&gt;This is why it&amp;rsquo;s important to design consciously&amp;mdash;you need to understand the ramifications and side-effects of certain design choices.&lt;/p&gt;
&lt;div style="margin:0px;padding:4px 0px 4px 0px;" class="wlWriterHeaderFooter"&gt;&lt;iframe style="border:none;width:325px;height:80px;" frameborder="0" scrolling="no" src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2013/01/21/idisposable-and-class-hierarchies.aspx"&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div style="margin:0px;padding:0px 0px 0px 0px;" class="wlWriterHeaderFooter"&gt;
&lt;script type="text/javascript"&gt;&lt;/script&gt;
&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1822950" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category></item><item><title>The Dispose Pattern as an anti-pattern</title><link>http://msmvps.com/blogs/peterritchie/archive/2013/01/20/the-dispose-pattern-as-an-anti-pattern.aspx</link><pubDate>Sun, 20 Jan 2013 22:16:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1822917</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1822917</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2013/01/20/the-dispose-pattern-as-an-anti-pattern.aspx#comments</comments><description>&lt;p&gt;When .NET first came out, the framework only had abstractions for what seemed like a handful of Windows features.&amp;nbsp; Developers were required to write their own abstractions around the Windows features that did not have abstractions.&amp;nbsp; Working with these features required you to work with unmanaged resources in many instances.&amp;nbsp; Unmanaged resources, as the name suggests, are not managed in any way by the .NET Framework.&amp;nbsp; If you don&amp;rsquo;t free those unmanaged resources when you&amp;rsquo;re done with them, they&amp;rsquo;ll leak.&amp;nbsp; Unmanaged resources need attention and they need it differently from managed resources.&amp;nbsp; Managed resources, by definition, are managed by the .NET Framework and their resources will be freed automatically a great proportion of the time when they&amp;rsquo;re no longer in use.&amp;nbsp; The Garbage Collector (GC) knows (or is &amp;ldquo;told&amp;rdquo;) what objects are in use and what objects are not in use.&lt;/p&gt;
&lt;p&gt;The GC frees managed resources when it gets its timeslice(s) to tidy up memory&amp;mdash;which will be some time *after* the resource stop being used.&amp;nbsp; The &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable&lt;/span&gt; interface was created so that managed resources can be deterministically freed.&amp;nbsp; I say &amp;ldquo;managed resources&amp;rdquo; because interfaces can do nothing with destructors and thus the interface inherently can&amp;rsquo;t do anything specifically to help with unmanaged resources.&lt;/p&gt;
&lt;p&gt;&amp;ldquo;Unmanaged resources&amp;rdquo; generally means dealing with a handle and freeing that handle when no longer in use.&amp;nbsp; &amp;ldquo;Support&amp;rdquo; for Windows features in .NET abstractions generally involved freeing those handles when not in use.&amp;nbsp; Much like managed resources, to deterministically free them you had to implement &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable&lt;/span&gt; and free them in the call to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt;.&amp;nbsp; The problem with this was if you forgot to wrap the object in a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;using&lt;/span&gt; block or otherwise didn&amp;rsquo;t call &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt;.&amp;nbsp; The managed resources would be detected as being unused (unreferenced) and be freed automatically at the next collection, unmanaged resources would not.&amp;nbsp; Unmanaged resources would leak and could cause potential issues with Windows in various ways (handles are a finite resource, for one, so an application could &amp;ldquo;run out&amp;rdquo;).&amp;nbsp; So, those unmanaged resources must be freed during finalization of the object (the automatic cleanup of the object during collection by the GC) had they not already been freed during dispose.&amp;nbsp; Since finalization and &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt; are intrinsically linked, the Dispose Pattern was created to make this process easier and consistent.&lt;/p&gt;
&lt;p&gt;I won&amp;rsquo;t get into much detail about the Dispose Pattern, but what this means is that to implement the Dispose Pattern, you must implement a destructor that calls &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(bool)&lt;/span&gt; with a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;false&lt;/span&gt; argument.&amp;nbsp; Destructors that do no work force an entry to be made in the finalize queue for each instance of that type.&amp;nbsp; This forces the type to use its memory until the GC has a chance to collect and run finalizers. This impacts performance (needless finalization) as well as adds stress to the garbage collector (extra work, more things to keep track of, extra resources, etc.). [1] If you have no unmanaged resources to free, you have no reason to have a destructor and thus have no reason to implement the Dispose Pattern.&amp;nbsp; Some might say it&amp;rsquo;s handy &amp;ldquo;just in case&amp;rdquo;; but those cases are &lt;em&gt;really rare&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;.NET has evolved quite a bit from version 1.x, it how has rich support for many of the Windows features that people need to be able to use.&amp;nbsp; Most of the type handles are hidden in these feature abstractions and the developer doesn&amp;rsquo;t need to do anything special other than recognize a type implements &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable&lt;/span&gt; and deterministically call &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt; in some way.&amp;nbsp; Of the features that didn&amp;rsquo;t have abstractions, lower-level abstractions like &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;SafeHandle&lt;/span&gt; (which &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;SafeHandleZeroOrMinusOneIsInvalid&lt;/span&gt; and &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;SafeHandleMinuesOneIsInvalid&lt;/span&gt; etc. derive from)&amp;mdash;which implement &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;IDisposable&lt;/span&gt; and makes every native handle a &amp;ldquo;managed resource&amp;rdquo;&amp;mdash;means &lt;strong&gt;there is very little reason to write a destructor&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The most recent perpetuation of the anti-pattern is in a Resharper extension called &lt;a href="http://blogs.jetbrains.com/dotnet/2013/01/r2p-a-general-purpose-resharper-plugin/"&gt;R2P&lt;/a&gt; (refactoring to patterns).&amp;nbsp; Let&amp;rsquo;s analyze the example R2P IDisposable code:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://blogs.jetbrains.com/dotnet/wp-content/uploads/2012/12/71.png" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;As we can see from this code, the Dispose pattern has been implemented and a destructor with a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(false)&lt;/span&gt;.&amp;nbsp; If we look at &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(bool)&lt;/span&gt;, &lt;strong&gt;&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(bool)&lt;/span&gt; does nothing if a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;false&lt;/span&gt; argument is passed to it&lt;/strong&gt;.&amp;nbsp; So, effectively we could simply remove &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(false)&lt;/span&gt; and get the same result.&amp;nbsp; This also means we could completely remove the destructor.&amp;nbsp; Now we&amp;rsquo;re left with &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(true)&lt;/span&gt; in &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose()&lt;/span&gt; and &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(bool)&lt;/span&gt;.&amp;nbsp; Since &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(bool)&lt;/span&gt; is now only ever called with a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;true&lt;/span&gt; argument, there&amp;rsquo;s no reason to have this method.&amp;nbsp; We can take the contents of the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;if(disposing)&lt;/span&gt; block, move it to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose&lt;/span&gt; (replacing the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(true)&lt;/span&gt;) and have exactly the same result as before &lt;strong&gt;without the Dispose Pattern&lt;/strong&gt;.&amp;nbsp; Except now, we&amp;rsquo;re reduced the stress on the GC *and* we&amp;rsquo;ve made our code much less complex.&amp;nbsp; Also, since we no longer have a destructor there will be no finalizer, so there&amp;rsquo;s no need to call &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;SuppressFinalize&lt;/span&gt;.&amp;nbsp; &lt;strong&gt;Not implementing the Dispose Pattern would result in better code&lt;/strong&gt; in this case:&lt;/p&gt;
&lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="font-size:12pt;"&gt;	&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Person&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; : &lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="color:#000000;"&gt; Dispose()
		{
			Photo.Dispose();
		}
 
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Bitmap&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; Photo { &lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;get&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;; &lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;set&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;; }
	}
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Of course, when you&amp;rsquo;re &lt;strong&gt;deriving from a class that implements the Dispose Pattern&lt;/strong&gt; &lt;em&gt;and your class needs to dispose of managed resources&lt;/em&gt;, then you need to make use of &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Dispose(bool)&lt;/span&gt;.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="font-size:12pt;"&gt;	&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;FantasicalControl&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; : System.Windows.Forms.&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Control&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;protected&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;override&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; Dispose(&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;bool&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt; disposing)
		{
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="color:#000000;"&gt;(disposing)
			{
				Photo.Dispose();
			}
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;base&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="font-size:12pt;"&gt;&lt;span style="color:#000000;"&gt;.Dispose(disposing);
		}
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;nbsp;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Bitmap&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; Photo { &lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;get&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;; &lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;set&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;; }
	}
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;h1&gt;&amp;nbsp;&lt;/h1&gt;
&lt;p&gt;Patterns are great, they help document code by providing consistent terminology and recognizable implementation (code).&amp;nbsp; But, when they&amp;rsquo;re not used in the right place at the right time, they make code confusing and harder to understand and become Anti-Patterns.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;[1] &lt;a title="http://bit.ly/YbBDAR" href="http://bit.ly/YbBDAR"&gt;http://bit.ly/YbBDAR&lt;/a&gt;&lt;/p&gt;
&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:4px 0px 4px 0px;"&gt;&lt;iframe src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2013/01/20/the-dispose-pattern-as-an-anti-pattern.aspx" scrolling="no" frameborder="0" style="border:none;width:325px;height:80px;"&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:0px 0px 0px 0px;"&gt;
&lt;script type="text/javascript"&gt;&lt;/script&gt;
&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1822917" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/AntiPattern/default.aspx">AntiPattern</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category></item><item><title>Thread synchronization of non-atomic invariants in .NET 4.5</title><link>http://msmvps.com/blogs/peterritchie/archive/2012/09/11/thread-synchronization-of-non-atomic-invariants-in-net-4-5.aspx</link><pubDate>Tue, 11 Sep 2012 19:04:02 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1816167</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1816167</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2012/09/11/thread-synchronization-of-non-atomic-invariants-in-net-4-5.aspx#comments</comments><description>&lt;p&gt;Now that we’ve seen how a singular x86-x64 focus &lt;a href="http://msmvps.com/blogs/peterritchie/archive/2012/09/09/thread-synchronization-of-atomic-invariants-in-net-4-5.aspx"&gt;might affect how we can synchronize atomic invariants&lt;/a&gt;, let’s look at non-atomic invariants.&lt;/p&gt;  &lt;p&gt;While an atomic invariant really doesn’t need much in the way of &lt;em&gt;guarding&lt;/em&gt;, non-atomic invariants often do.&amp;#160; The rules by which the invariant is correct are often much more complex.&amp;#160; Ensuring an atomic invariant like &lt;font face="Courier New"&gt;int&lt;/font&gt;, for example is pretty easy: you can’t set it to an invalid value, you just need to make sure the value is visible.&amp;#160; Non-atomic invariants involve data that can’t natively be modified atomically.&amp;#160; The typical case is more than one variable, but can include intrinsic types that are not guaranteed to be modified atomically (like long and decimal).&amp;#160; There is also the fact that not all operations on an atomic type are performed atomically.&lt;/p&gt;  &lt;p&gt;For example, let’s say I want to deal with a latitude longitude pair.&amp;#160; That pair of floating-point values is an invariant, I need to model accesses to that pair as an atomic operation.&amp;#160; If I write to &lt;font face="Courier New"&gt;latitude&lt;/font&gt;, that value shouldn’t be “seen” until I also write to &lt;font face="Courier New"&gt;longitude&lt;/font&gt;.&amp;#160; The following code does not guard that invariant in a concurrent context:&lt;/p&gt;  &lt;div id="codeSnippetWrapper"&gt;   &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;     &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;latitude = 39.73;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;longitude = -86.27;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;If somewhere else I changed these values, for example I wanted to change from the location of Indianapolis, IN to Ottawa, ON:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#606060;" id="lnum1"&gt;   1:&lt;/span&gt; latitude = 45.4112;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#606060;" id="lnum2"&gt;   2:&lt;/span&gt; longitude = -75.6981;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Another thread reading &lt;font face="Courier New"&gt;latitude&lt;/font&gt;/&lt;font face="Courier New"&gt;longitude&lt;/font&gt; if the thread was executing the above code was between line 1 and 2, would read a lat/long for some place near Newark instead of Ottawa or Indianapolis (the two lat/longs being written).&amp;#160; Making these write operations volatile does nothing to help make the operation atomic and thread-safe.&amp;#160; For example, the following is still not thread-safe:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#606060;" id="lnum1"&gt;   1:&lt;/span&gt; Thread.VolatileWrite(&lt;span style="color:#0000ff;"&gt;ref&lt;/span&gt; latitude, 45.4112);&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#606060;" id="lnum2"&gt;   2:&lt;/span&gt; Thread.VolatileWrite(&lt;span style="color:#0000ff;"&gt;ref&lt;/span&gt; longitude, -75.6981);&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A thread can still read &lt;font face="Courier New"&gt;latitude&lt;/font&gt; or &lt;font face="Courier New"&gt;longitude&lt;/font&gt; after line 1 executes on another thread and before line 2.&amp;#160; Given two variables that are publicly visible, the only way to make an operation on both “atomic” is to use &lt;font face="Courier New"&gt;lock&lt;/font&gt; or use a synchronization class like &lt;font face="Courier New"&gt;Monitor&lt;/font&gt;, &lt;font face="Courier New"&gt;Semaphore&lt;/font&gt;, &lt;font face="Courier New"&gt;Mutex&lt;/font&gt;, etc.&amp;#160; For example:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt;(latLongLock)&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;{&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    latitude = 45.4112;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    longitude = -75.6981;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Considering &lt;font face="Courier New"&gt;latitude&lt;/font&gt; and &lt;font face="Courier New"&gt;longitude&lt;/font&gt; “volatile”, doesn’t help us at all in this situation—we have to use &lt;font face="Courier New"&gt;lock&lt;/font&gt;.&amp;#160; And once we use &lt;font face="Courier New"&gt;lock&lt;/font&gt;, there’s no need to consider the variables volatile, no two threads can be in the same critical region at the same time, and any side-effect resulting from executing that critical region are guaranteed to be visible as soon as the lock is released. (as well any potentially visible side-effects from other threads are guaranteed to be visible as soon as the lock is acquired).&lt;/p&gt;

&lt;p&gt;There are circumstances where you can have loads/stores to different addresses that get reordered in relation to each other (a load can be reordered with older stores to a different memory address).&amp;#160; So, conceptually given two threads executing on different cores/CPUS executing the following code at the same time:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;x = 1;    |    y = 1;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;r1 = y;   |    r2 = x;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This could result in r1 == 0 and r2 == 0 (as described in section 8.2.3.2 of &lt;a href="http://download.intel.com/products/processor/manual/253668.pdf"&gt;Intel® 64 and IA-32 Architectures Software Developer’s Manual Volume 3A&lt;/a&gt;) assuming r1 and r2 access was optimized by the compiler to be an register access.&amp;#160; The only way to avoid this would be to force a memory barrier.&amp;#160; The use of &lt;font face="Courier New"&gt;volatile&lt;/font&gt;, as we’ve seen the prior post, is not enough to ensure a memory fence is invoked under all circumstances.&amp;#160; This can be done manually through the use of &lt;font face="Courier New"&gt;Thread.MemoryBarrier&lt;/font&gt;, or through the use of &lt;font face="Courier New"&gt;lock&lt;/font&gt;.&amp;#160; &lt;font face="Courier New"&gt;Thread.MemoryBarrier&lt;/font&gt; is less understood by a wide variety of developers, so using &lt;font face="Courier New"&gt;lock&lt;/font&gt; is almost always what should be used prior to any micro-optimizations.&amp;#160; For example:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt;(lockObject)&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;{&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;  x = 1;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;  r1 = y;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;and&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&amp;#160;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt;(lockObject)&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;{&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;  y = 1;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;  r2 = x;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This basically assumes &lt;font face="Courier New"&gt;x&lt;/font&gt; and &lt;font face="Courier New"&gt;y&lt;/font&gt; are involved in a particular invariant and that invariant needs to be guaranteed through atomic access to the pair of variables—which is done by creating a critical regions of code where only one region can be executing at a time across threads.&lt;/p&gt;

&lt;h3&gt;Revisiting the volatile keyword&lt;/h3&gt;

&lt;p&gt;The first post in this series could have came of as suggesting that &lt;font face="Courier New"&gt;volatile&lt;/font&gt; is always a good thing.&amp;#160; As we’ve seen in the above, that’s not true.&amp;#160; Let me be clear: using &lt;font face="Courier New"&gt;volatile&lt;/font&gt; in what I described previously is an optimization.&amp;#160; It should be a micro-optimization that should be used very, very carefully.&amp;#160; What is an isn’t an atomic invariant isn’t always cut and dry.&amp;#160; Not every operation on an atomic type is an atomic operation.&lt;/p&gt;

&lt;p&gt;Let’s look at some of the problems of &lt;font face="Courier New"&gt;volatile&lt;/font&gt;:&lt;/p&gt;

&lt;p&gt;The first, and arguably the most discussed problem, is that volatile decorates a variable not the use of that variable.&amp;#160; With non-atomic operations on an atomic variable, volatile can give you a false sense of security.&amp;#160; You may &lt;em&gt;think&lt;/em&gt; volatile gives you thread-safe code in all accesses to that variable, but it does not.&amp;#160; For example:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;volatile&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;int&lt;/span&gt; counter;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; DoSomething()&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;{&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    &lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    counter++;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    &lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Although many processors have a single instruction to increment an integer, “there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement” [1].&amp;#160; Despite counter being volatile, there’s no guarantee this operation will be atomic and thus there’s no guarantee that it will be thread-safe.&amp;#160; In the general case, not every type you can use operator++ on is atomic—looking strictly at “counter++;”, you can’t tell if that’s thread-safe..&amp;#160; If counter were of type long, access to counter is no longer atomic and a single instruction to increment it is only possible on some processors (regardless of lock of guarantees that it will be used). If counter were an atomic type, you’d have to check the declaration of the variable to see if it was volatile or not before deciding if it’s potentially thread-safe.&amp;#160;&amp;#160; To make incrementing a variable thread-safe, the &lt;font face="Courier New"&gt;Interlocked&lt;/font&gt; class should be used for supported types:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;int&lt;/span&gt; counter;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; DoSomething()&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;{&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    &lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    System.Threading.Interlocked.Increment(&lt;span style="color:#0000ff;"&gt;ref&lt;/span&gt; counter);&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    &lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Non-atomic types like &lt;font face="Courier New"&gt;long&lt;/font&gt;, &lt;font face="Courier New"&gt;ulong&lt;/font&gt; (i.e. not supported by &lt;font face="Courier New"&gt;volatile&lt;/font&gt;) are supported by &lt;font face="Courier New"&gt;Interlocked&lt;/font&gt;.&amp;#160; For non-atomic types not supported by &lt;font face="Courier New"&gt;Interlocked&lt;/font&gt;, &lt;font face="Courier New"&gt;lock&lt;/font&gt; is recommended until you’ve verified another method is “better” and works:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;decimal&lt;/span&gt; counter;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;readonly&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;object&lt;/span&gt; lockObject = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;object&lt;/span&gt;();&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; DoSomething()&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;{&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    &lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    &lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt;(lockObject)&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    {&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;        counter++;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    }&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:#f4f4f4;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;    &lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/pre&gt;


    &lt;pre style="border-bottom-style:none;text-align:left;padding-bottom:0px;line-height:12pt;background-color:white;margin:0em;border-left-style:none;padding-left:0px;width:100%;padding-right:0px;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;border-top-style:none;color:black;border-right-style:none;font-size:8pt;overflow:visible;padding-top:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;font face="Courier New"&gt;That is volatile&lt;/font&gt; is problematic because it can only be applied to member fields and only to certain types of member fields.&amp;#160; &lt;/p&gt;

&lt;p&gt;The general consensus is that because &lt;font face="Courier New"&gt;volatile&lt;/font&gt; doesn’t decorate the &lt;em&gt;operations&lt;/em&gt; that are potentially performed in a concurrent context, and doesn’t consistently lead to more efficient code in all circumstances, and passing a &lt;font face="Courier New"&gt;volatile&lt;/font&gt; field by ref circumvents the fields volatility, and would fail if used with non-atomic invariants, and lack of consistency with correctly guarded non-atomic operations, etc.; that the volatile operations should be explicit through the use of &lt;font face="Courier New"&gt;Interlocked&lt;/font&gt;, &lt;font face="Courier New"&gt;Thread.VolatileRead&lt;/font&gt;, &lt;font face="Courier New"&gt;Thread.VolatileWrite&lt;/font&gt;, or the use of &lt;font face="Courier New"&gt;lock&lt;/font&gt;&lt;font face="Verdana"&gt; and not through the use of the &lt;font face="Courier New"&gt;volatile&lt;/font&gt; keyword.&lt;/font&gt;&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Concurrent and multithreaded programming is not trivial.&amp;#160; It involves dealing with non-sequential operations through the writing of sequential code.&amp;#160; It’s prone to error and you really have to know the intent of your code in order to decide not only what might be used in a concurrent context as well as what is thread-safe.&amp;#160; i.e. “thread-safe” is application specific.&amp;#160; &lt;/p&gt;

&lt;p&gt;Despite only really having support for x86/x64 “out of the box” in .NET 4.5 (i.e. Visual Studio 2012), the &lt;strong&gt;potential side-effects of assuming an x86/x64 memory model just muddies the waters&lt;/strong&gt;.&amp;#160; I don’t think there is any benefit to writing to a x86/x64 memory model over writing to the .NET memory model.&amp;#160; Nothing I’ve shown really affects existing guidance on writing thread-safe and concurrent code—some of which are detailed in &lt;a href="http://bit.ly/Px43Pw"&gt;Visual Studio 2010 Best Practices&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Knowing what’s going on at lower levels in any particular situation is good, and anything you do in light of any side-effects should be considered micro-optimizations that should be well scrutinized.&lt;/p&gt;

&lt;p&gt;[1] C# Language Specification § 5.5 Atomicity of variable references&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:4px 0px 4px 0px;"&gt;&lt;iframe src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2012/09/11/thread-synchronization-of-non-atomic-invariants-in-net-4-5.aspx" scrolling="no" frameborder="0" style="border:none;width:325px;height:80px;"&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:0px 0px 0px 0px;"&gt;
&lt;script type="text/javascript"&gt;
  (function() {
    var po = document.createElement(&amp;#39;script&amp;#39;); po.type = &amp;#39;text/javascript&amp;#39;; po.async = true;
    po.src = &amp;#39;https://apis.google.com/js/plusone.js&amp;#39;;
    var s = document.getElementsByTagName(&amp;#39;script&amp;#39;)[0]; s.parentNode.insertBefore(po, s);
  })();
&lt;/script&gt;&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1816167" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Multithreaded/default.aspx">Multithreaded</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+4.5/default.aspx">.NET 4.5</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Concurrency/default.aspx">Concurrency</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2012/default.aspx">Visual Studio 2012</category></item><item><title>Thread synchronization of atomic invariants in .NET 4.5 clarifications</title><link>http://msmvps.com/blogs/peterritchie/archive/2012/09/10/thread-synchronization-of-atomic-invariants-in-net-4-5-clarifications.aspx</link><pubDate>Mon, 10 Sep 2012 19:26:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1816127</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1816127</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2012/09/10/thread-synchronization-of-atomic-invariants-in-net-4-5-clarifications.aspx#comments</comments><description>&lt;p&gt;In &lt;a href="http://msmvps.com/blogs/peterritchie/archive/2012/09/09/thread-synchronization-of-atomic-invariants-in-net-4-5.aspx"&gt;Thread synchronization of atomic invariants in .NET 4.5&lt;/a&gt; I&amp;rsquo;m presenting my observations of what the compiler does in very narrow context of only on Intel x86 and Intel x64 with a particular version of .NET.&amp;nbsp; You can install SDKs that give you access to compilers to other processors.&amp;nbsp; For example, if you write something for Windows Phone or Windows Store, you&amp;rsquo;ll get compilers for other processors (e.g. ARM) with memory models looser than x86 and x64.&amp;nbsp; That post was only observations in the context of x86 and x64.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;I believe more knowledge is always better; but you have to use that knowledge responsibly.&amp;nbsp; If you know you&amp;rsquo;re only ever going to target x86 or x64 (and you don&amp;rsquo;t if you use AnyCPU even in VS 2012 because some yet-to-be-created processor might be supported in a future version or update to .NET) and you &lt;em&gt;do want to micro-optimize your code&lt;/em&gt;, then that post might give you enough knowledge to do that.&amp;nbsp; Otherwise, take it with a grain of salt.&amp;nbsp; I&amp;rsquo;ll get into a little bit more detail in part 2: Thread synchronization of non-atomic invariants in .NET 4.5 at a future date&amp;mdash;which will include more specific guidance and recommendations.&lt;/p&gt;
&lt;p&gt;In the case were I used a &lt;em&gt;really awkwardly placed&lt;/em&gt; &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt;:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum1" style="color:#606060;"&gt;   1:&lt;/span&gt; var lockObject = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;object&lt;/span&gt;();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum2" style="color:#606060;"&gt;   2:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;while&lt;/span&gt; (!complete)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum3" style="color:#606060;"&gt;   3:&lt;/span&gt; {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum4" style="color:#606060;"&gt;   4:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt;(lockObject)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum5" style="color:#606060;"&gt;   5:&lt;/span&gt;     {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum6" style="color:#606060;"&gt;   6:&lt;/span&gt;         toggle = !toggle;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum7" style="color:#606060;"&gt;   7:&lt;/span&gt;     }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum8" style="color:#606060;"&gt;   8:&lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;It&amp;rsquo;s important to point out the degree of implicit side-effects that this code depends on.&amp;nbsp; One, it assumes that the compiler is smart enough to know that a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;while&lt;/span&gt; loop is the equivalent of a series of sequential statements.&amp;nbsp; e.g. this is effectively equivalent to:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum1" style="color:#606060;"&gt;   1:&lt;/span&gt; var lockObject = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;object&lt;/span&gt;();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum2" style="color:#606060;"&gt;   2:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;if&lt;/span&gt; (complete == &lt;span style="color:#0000ff;"&gt;false&lt;/span&gt;) &lt;span style="color:#0000ff;"&gt;return&lt;/span&gt;;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum3" style="color:#606060;"&gt;   3:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt; (lockObject)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum4" style="color:#606060;"&gt;   4:&lt;/span&gt; {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum5" style="color:#606060;"&gt;   5:&lt;/span&gt;     toggle = !toggle;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum6" style="color:#606060;"&gt;   6:&lt;/span&gt; }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum7" style="color:#606060;"&gt;   7:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;if&lt;/span&gt; (complete == &lt;span style="color:#0000ff;"&gt;false&lt;/span&gt;) &lt;span style="color:#0000ff;"&gt;return&lt;/span&gt;;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum8" style="color:#606060;"&gt;   8:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt; (lockObject)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum9" style="color:#606060;"&gt;   9:&lt;/span&gt; {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum10" style="color:#606060;"&gt;  10:&lt;/span&gt;     toggle = !toggle;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum11" style="color:#606060;"&gt;  11:&lt;/span&gt; }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum12" style="color:#606060;"&gt;  12:&lt;/span&gt; &lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;That is, there is the implicit volatile read (e.g. a memory fence, from the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Monitor.Enter&lt;/span&gt; implementation detail) at the start of the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; block and an implicit volatile write (e.g. a memory fence, from the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Monitor.Exit&lt;/span&gt; implementation detail).&lt;/p&gt;
&lt;p&gt;In case it wasn&amp;rsquo;t obvious, you should &lt;strong&gt;never write code like&lt;/strong&gt; this, it&amp;rsquo;s simply an example&amp;mdash;and as I pointed out in the original post, it&amp;rsquo;s confusing to anyone else reading it: &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lockObject&lt;/span&gt; can&amp;rsquo;t be shared amongst threads and the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; block really isn&amp;rsquo;t protecting &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;toggle&lt;/span&gt; and can/likely to get &amp;ldquo;maintained&amp;rdquo; into something that no longer works.&lt;/p&gt;
&lt;p&gt;In the same grain, the same can be said for the original example of this code:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum1" style="color:#606060;"&gt;   1:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Main()&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum2" style="color:#606060;"&gt;   2:&lt;/span&gt; {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum3" style="color:#606060;"&gt;   3:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;bool&lt;/span&gt; complete = &lt;span style="color:#0000ff;"&gt;false&lt;/span&gt;; &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum4" style="color:#606060;"&gt;   4:&lt;/span&gt;   var t = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; Thread (() =&amp;gt;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum5" style="color:#606060;"&gt;   5:&lt;/span&gt;   {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum6" style="color:#606060;"&gt;   6:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;bool&lt;/span&gt; toggle = &lt;span style="color:#0000ff;"&gt;false&lt;/span&gt;;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum7" style="color:#606060;"&gt;   7:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;while&lt;/span&gt; (!complete)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum8" style="color:#606060;"&gt;   8:&lt;/span&gt;     {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum9" style="color:#606060;"&gt;   9:&lt;/span&gt;         Thread.MemoryBarrier();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum10" style="color:#606060;"&gt;  10:&lt;/span&gt;         toggle = !toggle;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum11" style="color:#606060;"&gt;  11:&lt;/span&gt;     }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum12" style="color:#606060;"&gt;  12:&lt;/span&gt;   });&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum13" style="color:#606060;"&gt;  13:&lt;/span&gt;   t.Start();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum14" style="color:#606060;"&gt;  14:&lt;/span&gt;   Thread.Sleep (1000);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum15" style="color:#606060;"&gt;  15:&lt;/span&gt;   complete = &lt;span style="color:#0000ff;"&gt;true&lt;/span&gt;;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum16" style="color:#606060;"&gt;  16:&lt;/span&gt;   t.Join();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum17" style="color:#606060;"&gt;  17:&lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;While this code works, it&amp;rsquo;s not apparently clear that the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.MemoryBarrier()&lt;/span&gt; is there so that our read of &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;complete&lt;/span&gt; (and not &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;toggle&lt;/span&gt;) isn&amp;rsquo;t optimized into a registry read.&amp;nbsp; Regardless of the degree you might be able to depend on the compiler continuing to do this is up to you.&amp;nbsp; The code is equally as valid and more clear if written to use &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;, except for the fact that &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt; does not support the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Boolean&lt;/span&gt; type.&amp;nbsp; It can be re-written using &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Int32&lt;/span&gt; instead.&amp;nbsp; For example:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum1" style="color:#606060;"&gt;   1:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Main(&lt;span style="color:#0000ff;"&gt;string&lt;/span&gt;[] args)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum2" style="color:#606060;"&gt;   2:&lt;/span&gt; {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum3" style="color:#606060;"&gt;   3:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;int&lt;/span&gt; complete = 0; &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum4" style="color:#606060;"&gt;   4:&lt;/span&gt;   var t = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; Thread (() =&amp;gt;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum5" style="color:#606060;"&gt;   5:&lt;/span&gt;   {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum6" style="color:#606060;"&gt;   6:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;bool&lt;/span&gt; toggle = &lt;span style="color:#0000ff;"&gt;false&lt;/span&gt;;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum7" style="color:#606060;"&gt;   7:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;while&lt;/span&gt; (Thread.VolatileRead(&lt;span style="color:#0000ff;"&gt;ref&lt;/span&gt; complete) == 0)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum8" style="color:#606060;"&gt;   8:&lt;/span&gt;     {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum9" style="color:#606060;"&gt;   9:&lt;/span&gt;         toggle = !toggle;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum10" style="color:#606060;"&gt;  10:&lt;/span&gt;     }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum11" style="color:#606060;"&gt;  11:&lt;/span&gt;   });&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum12" style="color:#606060;"&gt;  12:&lt;/span&gt;   t.Start();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum13" style="color:#606060;"&gt;  13:&lt;/span&gt;   Thread.Sleep (1000);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum14" style="color:#606060;"&gt;  14:&lt;/span&gt;   complete = 1; // CORRECTION from 0&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum15" style="color:#606060;"&gt;  15:&lt;/span&gt;   t.Join();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum16" style="color:#606060;"&gt;  16:&lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Which is more clear and shows your intent more explicitly.&lt;/p&gt;
&lt;div style="margin:0px;padding:4px 0px 4px 0px;" class="wlWriterHeaderFooter"&gt;&lt;iframe style="border:none;width:325px;height:80px;" frameborder="0" scrolling="no" src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2012/09/10/thread-synchronization-of-atomic-invariants-in-net-4-5-clarifications.aspx"&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div style="margin:0px;padding:0px 0px 0px 0px;" class="wlWriterHeaderFooter"&gt;
&lt;script type="text/javascript"&gt;&lt;/script&gt;
&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1816127" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Multithreaded/default.aspx">Multithreaded</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+4.5/default.aspx">.NET 4.5</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Concurrency/default.aspx">Concurrency</category></item><item><title>Thread synchronization of atomic invariants in .NET 4.5</title><link>http://msmvps.com/blogs/peterritchie/archive/2012/09/09/thread-synchronization-of-atomic-invariants-in-net-4-5.aspx</link><pubDate>Sun, 09 Sep 2012 16:52:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1816066</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1816066</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2012/09/09/thread-synchronization-of-atomic-invariants-in-net-4-5.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ve written before about multi-threaded programming in .NET (C#).&amp;nbsp; Spinning up threads and executing code on another thread isn&amp;#39;t really the hard part.&amp;nbsp; The hard part is synchronization of data between threads.&lt;/p&gt;
&lt;p&gt;Most of what I&amp;#39;ve written about is from a processor agnostic point of view.&amp;nbsp; It&amp;#39;s written from the historical point of view: that .NET supports many processors with varying memory models.&amp;nbsp; The stance has generally been that you&amp;#39;re programming for the .NET memory model and not a particular processor memory model.&lt;/p&gt;
&lt;p&gt;But, that&amp;#39;s no longer entirely true.&amp;nbsp; In 2010 Microsoft basically dropped support for Itanium in both Windows Server and in Visual Studio (&lt;a href="http://blogs.technet.com/b/windowsserver/archive/2010/04/02/windows-server-2008-r2-to-phase-out-itanium.aspx"&gt;http://blogs.technet.com/b/windowsserver/archive/2010/04/02/windows-server-2008-r2-to-phase-out-itanium.aspx)&lt;/a&gt;.&amp;nbsp; In VS 2012 there is no &amp;ldquo;Itanium&amp;rdquo; choice in the project Build options.&amp;nbsp; As far as I can tell, Windows 2008 R2 is the only Windows operating system, still in support, that supports Itanium.&amp;nbsp; And even Windows 2008 R2 for Itanium is not supported for .NET 4.5 (&lt;a href="http://msdn.microsoft.com/en-us/library/8z6watww.aspx"&gt;http://msdn.microsoft.com/en-us/library/8z6watww.aspx)&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So, what does this mean to really only have the context of running only x86/x64?&amp;nbsp; Well, if you really read the documentation and research the Intel x86 and x64 memory model this could have an impact in how you write multi-threaded code with regard to shared data synchronization.&amp;nbsp; x86 and x64 memory models include guarantees like &amp;ldquo;In a multiple-processor system&amp;hellip;Writes by a single processor are observed in the same order by all processors.&amp;rdquo; &lt;span style="text-decoration:line-through;"&gt;but does&lt;/span&gt;&amp;nbsp;&lt;span style="text-decoration:underline;"&gt;and also&lt;/span&gt; includes guarantees like &amp;ldquo;Loads May Be Reordered with Earlier Stores to Different Locations&amp;rdquo;.&amp;nbsp; What this really means is that a store or a load to a single location won&amp;rsquo;t be reordered with regard to a load or a store to the same location across processors.&amp;nbsp; That is we don&amp;rsquo;t &lt;em&gt;need&lt;/em&gt; fences to ensure a store to a single memory location is &amp;ldquo;seen&amp;rdquo; by all threads or that a load from memory loads the &amp;ldquo;most recent&amp;rdquo; value stored.&amp;nbsp; But, it does mean that in order for &lt;em&gt;multiple stores&lt;/em&gt; to &lt;em&gt;multiple locations&lt;/em&gt; to be viewed by other threads &lt;em&gt;in the same order&lt;/em&gt;, a fence is necessary (or the group of store operations is invoked as an atomic action through the user of synchronization primitives like Monitor.Enter/Exit, lock, Semaphore, etc.) (See section 8.2 Memory Ordering&amp;nbsp; of the &lt;a href="http://download.intel.com/products/processor/manual/253668.pdf"&gt;Intel Software Developer&amp;rsquo;s Manual Volume 3A&lt;/a&gt; found &lt;a href="http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html"&gt;here&lt;/a&gt;).&amp;nbsp; But, that deals with non-atomic invariants which I&amp;rsquo;ll detail in another post.&lt;/p&gt;
&lt;p&gt;To be clear, you could develop to just x86 or just x64 prior to .NET 4.5 and have all the issues I&amp;rsquo;m about to detail.&lt;/p&gt;
&lt;p&gt;Prior to .NET 4.5 you really programmed to the .NET memory model.&amp;nbsp; This has changed over time since ECMA defined it around .NET 2.0; but that model was meant to be a &amp;ldquo;supermodel&amp;rdquo; to deal with the fact that .NET could be deployed to different CPUs with disparate memory models.&amp;nbsp; Most notably was the Itanium memory model.&amp;nbsp; This model is much looser than the Intel x86 memory model and allowed things like a store without a release fence and a load without an acquire fence.&amp;nbsp; This meant that a load or a store might be done only in one CPU&amp;rsquo;s memory cache and wouldn&amp;rsquo;t be flushed to memory until a fence.&amp;nbsp; This also meant that other CPUs (e.g. other threads) may not see the store or may not get the &amp;quot;latest&amp;quot; value with a load.&amp;nbsp; You can explicitly cause release and acquire fences with .NET with things like &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Monitor.Enter&lt;/span&gt;/&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Exit&lt;/span&gt; (&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt;), &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Interlocked&lt;/span&gt; methods, &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.MemoryBarrier&lt;/span&gt;, &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;/&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;VolatileWrite&lt;/span&gt;, etc.&amp;nbsp; So, it wasn&amp;#39;t a big issue for .NET programmers to write code that would work on an Itanium.&amp;nbsp; For the most part, if you simply guarded all your shared data with a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt;, you were fine.&amp;nbsp; &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; is expensive, so you could optimize things with &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;/&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;VolatileWriter&lt;/span&gt; if your shared data was inherently atomic (like a single &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;int&lt;/span&gt;, a single &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Object&lt;/span&gt;, etc) or you could use the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt; keyword (in C#).&amp;nbsp; The conventional wisdom has been to use &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;/&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;VolatileWrite&lt;/span&gt; rather than decorate a field with &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt; because you may not need &lt;em&gt;every&lt;/em&gt; access to be &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt; and you don&amp;rsquo;t want to take the performance hit when it doesn&amp;rsquo;t &lt;em&gt;need&lt;/em&gt; to be &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;For example (borrowed from &lt;a href="http://www.lidnug.org/archives.aspx"&gt;Jeffrey Richter&lt;/a&gt;, but slightly modified) shows synchronizing a static member variable with &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;/&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;VolatileWrite&lt;/span&gt;:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum1" style="color:#606060;"&gt;   1:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;class&lt;/span&gt; Program {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum2" style="color:#606060;"&gt;   2:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;int&lt;/span&gt; s_stopworker;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum3" style="color:#606060;"&gt;   3:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Main() {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum4" style="color:#606060;"&gt;   4:&lt;/span&gt;     Console.WriteLine(&lt;span style="color:#006080;"&gt;&amp;quot;Main: letting worker run for 5 seconds&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum5" style="color:#606060;"&gt;   5:&lt;/span&gt;     Thread t = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; Thread(Worker);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum6" style="color:#606060;"&gt;   6:&lt;/span&gt;     t.Start();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum7" style="color:#606060;"&gt;   7:&lt;/span&gt;     Thread.Sleep(5000);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum8" style="color:#606060;"&gt;   8:&lt;/span&gt;     Thread.VolatileWrite(&lt;span style="color:#0000ff;"&gt;ref&lt;/span&gt; s_stopworker, 1);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum9" style="color:#606060;"&gt;   9:&lt;/span&gt;     Console.WriteLine(&lt;span style="color:#006080;"&gt;&amp;quot;Main: waiting for worker to stop&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum10" style="color:#606060;"&gt;  10:&lt;/span&gt;     t.Join();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum11" style="color:#606060;"&gt;  11:&lt;/span&gt;   }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum12" style="color:#606060;"&gt;  12:&lt;/span&gt;  &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum13" style="color:#606060;"&gt;  13:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Worker(&lt;span style="color:#0000ff;"&gt;object&lt;/span&gt; o) {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum14" style="color:#606060;"&gt;  14:&lt;/span&gt;     Int32 x = 0;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum15" style="color:#606060;"&gt;  15:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;while&lt;/span&gt;(Thread.VolatileRead(&lt;span style="color:#0000ff;"&gt;ref&lt;/span&gt; s_stopworker) == 0)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum16" style="color:#606060;"&gt;  16:&lt;/span&gt;     {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum17" style="color:#606060;"&gt;  17:&lt;/span&gt;       x++;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum18" style="color:#606060;"&gt;  18:&lt;/span&gt;     }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum19" style="color:#606060;"&gt;  19:&lt;/span&gt;   }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum20" style="color:#606060;"&gt;  20:&lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id="codeSnippetWrapper"&gt;&amp;nbsp;&lt;/div&gt;
&lt;div&gt;Without the call to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileWrite&lt;/span&gt; the processor could reorder the write of 1 to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;s_stopworker&lt;/span&gt; to after the read (assuming we&amp;rsquo;re not developing to on particular processor memory model and we&amp;rsquo;re including Itanium).&amp;nbsp; In terms of the compiler, without &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt; it could cache the value being read from s_stopworker in to a register.&amp;nbsp; For example, removing the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;, the compiler optimizes the comparison of &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;s_stopworker&lt;/span&gt; to 0 in the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;while&lt;/span&gt; to single register (on x86):&lt;/div&gt;
&lt;div&gt;&amp;nbsp;&lt;/div&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000000  push        ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000001  mov         ebp,esp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000003  mov         eax,dword ptr ds:[00213360h] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000008  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000a  jne         00000010 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000c  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000e  je          0000000C &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000010  pop         ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000011  ret &lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The loop is 0000000c to 0000000e (really just testing that the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;eax&lt;/span&gt; register is 0). Using &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;, we&amp;rsquo;d always get a value from a physical memory location:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000000  push        ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000001  mov         ebp,esp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000003  lea         ecx,ds:[00193360h] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000009  call        71070480 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000e  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000010  jne         00000021 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000012  lea         ecx,ds:[00193360h] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000018  call        71070480 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000001d  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000001f  je          00000012 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000021  pop         ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000022  ret &lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The loop is now 00000012 to 0000001f, which shows calling &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt; each iteration (location 00000018). But, as we&amp;rsquo;ve seen from the Intel documentation and guidance, we don&amp;rsquo;t really need to call &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;VolatileRead&lt;/span&gt;, we just don&amp;rsquo;t want the compiler to optimize the memory access away into a register access. This code &lt;em&gt;works&lt;/em&gt;, but we take the hit of calling &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;VolatileRead&lt;/span&gt; which forces a memory fence through a call to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.MemoryBarrier&lt;/span&gt; after reading the value.&amp;nbsp; For example, the following code is equivalent:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span style="color:#0000ff;"&gt;while&lt;/span&gt;(s_stopworker == 0)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;{&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;  Thread.MemoryBarrier();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;  x++;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;And this works equally as well as using &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;, and compiles down to:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000000  push        ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000001  mov         ebp,esp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000003  cmp         dword ptr ds:[002A3360h],0 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000a  jne         0000001A &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000c  &lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt; or     dword ptr [esp],0 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000011  cmp         dword ptr ds:[002A3360h],0 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000018  je          0000000C &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000001a  pop         ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000001b  ret &lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The loop is now is 0000000c to 00000018. As we can see at 0000000c we have an extra &amp;ldquo;lock or&amp;rdquo; instruction&amp;mdash;which is what the compiler optimizes a call to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.MemoryBarrier&lt;/span&gt; to. This instruction really just or&amp;rsquo;s 0 with what &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;esp&lt;/span&gt; is pointing to (i.e. &amp;ldquo;nothing&amp;rdquo;, zero or&amp;rsquo;ed with something else does not change the value). But the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; prefix forces a fence and is less expensive than instructions like &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;mfence&lt;/span&gt;. But, based on what we know of the x86/x64 memory model, we&amp;rsquo;re only dealing with a single memory location and we don&amp;rsquo;t &lt;em&gt;need&lt;/em&gt; that &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; prefix&amp;mdash;the inherent memory guarantees of the processor means that our thread can see any and all writes to that memory location without this extra fence. So, what can we do to get rid of it? Well, using &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt; actually results in code that doesn&amp;rsquo;t generate that &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock or&lt;/span&gt; instruction. For example, if we change our code to make &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;s_stopworker&lt;/span&gt; &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt;:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum1" style="color:#606060;"&gt;   1:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;class&lt;/span&gt; Program {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum2" style="color:#606060;"&gt;   2:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;private&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;volatile&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;int&lt;/span&gt; s_stopworker;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum3" style="color:#606060;"&gt;   3:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Main() {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum4" style="color:#606060;"&gt;   4:&lt;/span&gt;     Console.WriteLine(&lt;span style="color:#006080;"&gt;&amp;quot;Main: letting worker run for 5 seconds&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum5" style="color:#606060;"&gt;   5:&lt;/span&gt;     Thread t = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; Thread(Worker);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum6" style="color:#606060;"&gt;   6:&lt;/span&gt;     t.Start();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum7" style="color:#606060;"&gt;   7:&lt;/span&gt;     Thread.Sleep(5000);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum8" style="color:#606060;"&gt;   8:&lt;/span&gt;     s_stopworker = 1;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum9" style="color:#606060;"&gt;   9:&lt;/span&gt;     Console.WriteLine(&lt;span style="color:#006080;"&gt;&amp;quot;Main: waiting for worker to stop&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum10" style="color:#606060;"&gt;  10:&lt;/span&gt;     t.Join();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum11" style="color:#606060;"&gt;  11:&lt;/span&gt;   }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum12" style="color:#606060;"&gt;  12:&lt;/span&gt;  &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum13" style="color:#606060;"&gt;  13:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Worker(&lt;span style="color:#0000ff;"&gt;object&lt;/span&gt; o) {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum14" style="color:#606060;"&gt;  14:&lt;/span&gt;     Int32 x = 0;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum15" style="color:#606060;"&gt;  15:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;while&lt;/span&gt;(s_stopworker == 0)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum16" style="color:#606060;"&gt;  16:&lt;/span&gt;     {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum17" style="color:#606060;"&gt;  17:&lt;/span&gt;       x++;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum18" style="color:#606060;"&gt;  18:&lt;/span&gt;     }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum19" style="color:#606060;"&gt;  19:&lt;/span&gt;   }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum20" style="color:#606060;"&gt;  20:&lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;We tell the compiler that we don&amp;rsquo;t want accesses to s_stopworker optimized.&amp;nbsp; This then compiles down to:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000000  push        ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000001  mov         ebp,esp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000003  cmp         dword ptr ds:[00163360h],0 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000a  jne         00000015 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000c  cmp         dword ptr ds:[00163360h],0 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000013  je          0000000C &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000015  pop         ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000016  ret &lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The loop is now 0000000c to 00000013. Notice that we&amp;rsquo;re simply getting the value from memory on each iteration and comparing it to 0. There&amp;rsquo;s no &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock or&lt;/span&gt;. One less instruction and no extra memory fence. Although in many cases it doesn&amp;rsquo;t matter (i.e. you might only do this once, in which case an extra few milliseconds won&amp;rsquo;t hurt and this might be a premature optimization), but using &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock or&lt;/span&gt; with the register optimization is about 992% slower when measured on my computer (or &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt; is 91% faster than using &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.MemoryBarrier&lt;/span&gt; and probably a bit faster still than use &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt;).&amp;nbsp; This is actually contradictory to conventional wisdom with respect to a .NET memory model that supports Itanium.&amp;nbsp; If you want to support Itanium, every access to a &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt; field would be tantamount to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileRead&lt;/span&gt; or &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.VolatileWrite&lt;/span&gt;, in which case, yes, in scenarios where you don&amp;rsquo;t really need the field to be &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt;, you take a performance hit.&lt;/p&gt;
&lt;p&gt;In .NET 4.5 where Itanium is out of the picture, you might be thinking &amp;ldquo;volatile all the time then!&amp;rdquo;.&amp;nbsp; But, hold on a minute, let&amp;rsquo;s look at another example:&lt;/p&gt;
&lt;p id="codeSnippetWrapper"&gt;&amp;nbsp;&lt;/p&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum1" style="color:#606060;"&gt;   1:&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Main()&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum2" style="color:#606060;"&gt;   2:&lt;/span&gt; {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum3" style="color:#606060;"&gt;   3:&lt;/span&gt;   &lt;span style="color:#0000ff;"&gt;bool&lt;/span&gt; complete = &lt;span style="color:#0000ff;"&gt;false&lt;/span&gt;; &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum4" style="color:#606060;"&gt;   4:&lt;/span&gt;   var t = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; Thread (() =&amp;gt;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum5" style="color:#606060;"&gt;   5:&lt;/span&gt;   {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum6" style="color:#606060;"&gt;   6:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;bool&lt;/span&gt; toggle = &lt;span style="color:#0000ff;"&gt;false&lt;/span&gt;;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum7" style="color:#606060;"&gt;   7:&lt;/span&gt;     &lt;span style="color:#0000ff;"&gt;while&lt;/span&gt; (!complete)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum8" style="color:#606060;"&gt;   8:&lt;/span&gt;     {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum9" style="color:#606060;"&gt;   9:&lt;/span&gt;         Thread.MemoryBarrier();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum10" style="color:#606060;"&gt;  10:&lt;/span&gt;         toggle = !toggle;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum11" style="color:#606060;"&gt;  11:&lt;/span&gt;     }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum12" style="color:#606060;"&gt;  12:&lt;/span&gt;   });&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum13" style="color:#606060;"&gt;  13:&lt;/span&gt;   t.Start();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum14" style="color:#606060;"&gt;  14:&lt;/span&gt;   Thread.Sleep (1000);&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum15" style="color:#606060;"&gt;  15:&lt;/span&gt;   complete = &lt;span style="color:#0000ff;"&gt;true&lt;/span&gt;;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum16" style="color:#606060;"&gt;  16:&lt;/span&gt;   t.Join();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span id="lnum17" style="color:#606060;"&gt;  17:&lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;This code (borrowed from &lt;a href="http://www.albahari.com/threading/part4.aspx"&gt;Joe Albahari&lt;/a&gt;) will block indefinitely at the call to Thread.Join (line 16) without the call to Thread.MemoryBarrier() (at line 9).&amp;nbsp; &lt;/p&gt;
&lt;p&gt;This code blocks indefinitely without &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.MemoryBarrier()&lt;/span&gt; on both x86 and x64; but this is due to compiler optimizations, not because of the processor&amp;rsquo;s memory model. We can see this in the disassembly of what the JIT produces for the thread lambda (on x64):&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000000  push        ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000001  mov         ebp,esp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000003  movzx       eax,&lt;span style="color:#0000ff;"&gt;byte&lt;/span&gt; ptr [ecx+4] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000007  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000009  jne         0000000F &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000b  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000d  je          0000000B &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000000f  pop         ebp &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000010  ret &lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Notice the loop (0000000b to 0000000d), the compiler has optimized access to the variable toggle into a register and doesn&amp;rsquo;t update that register from memory&amp;mdash;identical to what we saw with the member field above. If we see the disassembly when using MemoryBarrier:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000000  movzx       eax,&lt;span style="color:#0000ff;"&gt;byte&lt;/span&gt; ptr [rcx+8] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000004  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000006  jne         0000000000000020 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000008  nop         dword ptr [rax+rax+00000000h] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000010  &lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt; or     dword ptr [rsp],0 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000015  movzx       eax,&lt;span style="color:#0000ff;"&gt;byte&lt;/span&gt; ptr [rcx+8] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000019  test        eax,eax &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000001b  je          0000000000000010 &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;0000001d  nop         dword ptr [rax] &lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;00000020  rep ret &lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;We see that loop testing &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;toggle&lt;/span&gt; (instructions from 00000010 to 0000001b) grabs the memory value into &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;eax&lt;/span&gt; then tests &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;eax&lt;/span&gt; until it&amp;rsquo;s true (or non-zero). &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;MemoryBarrier&lt;/span&gt; has been optimized to &amp;ldquo;lock or&amp;rdquo; here as well.&lt;/p&gt;
&lt;p&gt;What we&amp;rsquo;re dealing with here is a &lt;strong&gt;local variable&lt;/strong&gt; and &lt;strong&gt;can&amp;rsquo;t use the volatile keyword&lt;/strong&gt;.&amp;nbsp; We could use the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; keyword to get a fence, it couldn&amp;rsquo;t be around the comparison (the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;while&lt;/span&gt;) because that would enclose the entire &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;while&lt;/span&gt; block and would never exit the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; to get the memory fence and thus the compiler believes reads of &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;toggle&lt;/span&gt; aren&amp;rsquo;t guarded by &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt;&amp;rsquo;s implicit fences.&amp;nbsp; We&amp;rsquo;d have to wrap &lt;em&gt;the assignment&lt;/em&gt; to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;toggle&lt;/span&gt; to get the release fence before and the acquire fence after, ala:&lt;/p&gt;
&lt;div id="codeSnippetWrapper"&gt;
&lt;div id="codeSnippet" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;
&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;var lockObject = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;object&lt;/span&gt;();&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;&lt;span style="color:#0000ff;"&gt;while&lt;/span&gt; (!complete)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;{&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;    &lt;span style="color:#0000ff;"&gt;lock&lt;/span&gt;(lockObject)&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;    {&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;        toggle = !toggle;&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:white;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;    }&lt;/pre&gt;

&lt;pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;margin:0em;width:100%;font-family:&amp;#39;Courier New&amp;#39;, courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;padding:0px;"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Clearly this &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lock&lt;/span&gt; block isn&amp;rsquo;t really a critical section because the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;lockObject&lt;/span&gt; instance can&amp;rsquo;t be shared amongst threads.&amp;nbsp; Anyone reading this code is likely going to think &amp;ldquo;WTF?&amp;rdquo;. But, &lt;em&gt;we do&lt;/em&gt; get our fences, and the compiler will not optimize access to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;toggle&lt;/span&gt; to only a register and our code will no longer block at the call to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.Join&lt;/span&gt;.&amp;nbsp; It&amp;rsquo;s apparent that &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Thread.MemoryBarrier&lt;/span&gt; is the better choice in this scenario, it&amp;rsquo;s just more readable and doesn&amp;rsquo;t appear to be poorly written code (i.e. code that only depends on side effects).&lt;/p&gt;
&lt;p&gt;But, you still take the performance hit on &amp;ldquo;lock or&amp;rdquo;.&amp;nbsp; If you want to avoid that, then refactor the local &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;toggle&lt;/span&gt; variable to a field and decorate it with &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;volatile&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Although some of this seems like micro-optimizations, but it&amp;rsquo;s not.&amp;nbsp; You have to be careful to &amp;ldquo;synchronize&amp;rdquo; shared atomic data with respect to compiler optimizations, so you might as well pick the best way that works.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In the next post I&amp;rsquo;ll get into synchronizing non-atomic invariants shared amongst threads.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;div style="margin:0px;padding:4px 0px 4px 0px;" class="wlWriterHeaderFooter"&gt;&lt;iframe style="border:none;width:325px;height:80px;" frameborder="0" scrolling="no" src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2012/09/09/thread-synchronization-in-net-4-5.aspx"&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div style="margin:0px;padding:0px 0px 0px 0px;" class="wlWriterHeaderFooter"&gt;
&lt;script type="text/javascript"&gt;&lt;/script&gt;
&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1816066" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Multithreaded/default.aspx">Multithreaded</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+4.5/default.aspx">.NET 4.5</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Concurrency/default.aspx">Concurrency</category></item><item><title>Visual Studio 2010 Best Practices published</title><link>http://msmvps.com/blogs/peterritchie/archive/2012/08/25/visual-studio-2010-best-practices-published.aspx</link><pubDate>Sat, 25 Aug 2012 22:12:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1815504</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1815504</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2012/08/25/visual-studio-2010-best-practices-published.aspx#comments</comments><description>&lt;p&gt;Most of my spare time in the last few months has been taken up by writing &lt;i&gt;Visual Studio 2010 Best Practices&lt;/i&gt;.&amp;nbsp; This has now been published and is available through publisher (no longer pre-order) at &lt;a href="http://bit.ly/Px43Pw"&gt;http://bit.ly/Px43Pw&lt;/a&gt;.&amp;nbsp; The pre-order price is still available for a limited time.&amp;nbsp; Amazon still has it out of stock; but $39.99 at&amp;nbsp;&lt;a href="http://amzn.to/QDDmF7"&gt;&lt;b&gt;http://&lt;/b&gt;amzn.to/QDDmF7&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The title of the book really doesn&amp;#39;t do the content justice.&amp;nbsp; Least of which is &amp;quot;Best Practices&amp;quot;.&amp;nbsp; Anyone who knows me should know I don&amp;#39;t really like that term.&amp;nbsp; But, hopefully those looking for best practices will read the book and learn from chapter one why &amp;quot;best practice&amp;quot; has problems.&lt;/p&gt;
&lt;p&gt;While it&amp;#39;s called &amp;quot;Visual Studio 2010 Best Practices&amp;quot; it isn&amp;#39;t limited to the UI of Visual Studio (or Visual Studio 2010 really, for that matter).&amp;nbsp; It&amp;#39;s really a set of generally accepted recommended practices based on expertise and experience for any and all developers of .NET (it assumes they use Visual Studio--but many practices deal with general design/development that can be applied almost anywhere).&amp;nbsp; There are some specifics in there about the Visual Studio UI like optimizing Visual Studio settings/configuration, useful features, the correct way to use certain features, etc.&amp;nbsp; But, that&amp;#39;s mostly limited to one chapter.&amp;nbsp; Other chapters include recommended practices regarding C#, SCC, deployment, testing, parallelization/multithreading, distributed applications and web services.&amp;nbsp; From the book overview:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Learning source code control &lt;/li&gt;
&lt;li&gt;Practices for advanced C# syntax &lt;/li&gt;
&lt;li&gt;Asynchronous programming in C# &lt;/li&gt;
&lt;li&gt;Learn tips for architecting decoupled systems &lt;/li&gt;
&lt;li&gt;Practices for designing multi-threaded and parallel systems &lt;/li&gt;
&lt;li&gt;Practices for designing distributed systems &lt;/li&gt;
&lt;li&gt;Learn better ways of developing web services with WCF &lt;/li&gt;
&lt;li&gt;Learn faster ways to design automated tests &lt;/li&gt;
&lt;li&gt;Tips and tricks to test complex systems &lt;/li&gt;
&lt;li&gt;Understanding proven ways of deploying software systems in Windows&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Kind of a mixed bag; but, you have to work within the bounds you&amp;#39;ve been given :).&amp;nbsp; It was limited to about 200 pages; so, of course, I couldn&amp;rsquo;t go into every recommended practice or every useful tidbit that everyone could use&amp;hellip;&lt;/p&gt;
&lt;p&gt;I&amp;#39;d like to thank a few people for helping-out outside of the publisher&amp;#39;s review channel (i.e. they&amp;#39;re not mentioned in the book):&amp;nbsp; Joe Miller, Amir Barylko, and of course all those that offered&amp;hellip;&lt;/p&gt;
&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:4px 0px 4px 0px;"&gt;&lt;iframe scrolling="no" frameborder="0" src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2012/08/25/visual-studio-2010-best-practices-published.aspx" style="width:325px;height:80px;"&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:0px 0px 0px 0px;"&gt;
&lt;script type="text/javascript"&gt;&lt;/script&gt;
&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1815504" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Practices/default.aspx">Software Development Practices</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2010/default.aspx">Visual Studio 2010</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Principles/default.aspx">Software Development Principles</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+studio+2010+Best+Practices/default.aspx">Visual studio 2010 Best Practices</category></item><item><title>Automated Testing Isn’t Just for Business Logic</title><link>http://msmvps.com/blogs/peterritchie/archive/2012/05/25/automated-testing-isn-t-just-for-business-logic.aspx</link><pubDate>Fri, 25 May 2012 17:51:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1810302</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1810302</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2012/05/25/automated-testing-isn-t-just-for-business-logic.aspx#comments</comments><description>&lt;p&gt;I had a conversation with &lt;a href="http://bit.ly/LAcF5n"&gt;Kelly Sommers&lt;/a&gt; the other day that was partially a short &lt;em&gt;support group session&lt;/em&gt; on the annoying tendencies of development teams to completely lose focus on the architecture and design principles of a system and let the code base devolve into a ball of muddy spaghetti.&lt;/p&gt;
&lt;p&gt;One particular area that we discussed, and it&amp;rsquo;s one area I&amp;rsquo;ve detailed &lt;a href="http://bit.ly/c13trs"&gt;elsewhere&lt;/a&gt;, has to do with layers.&amp;nbsp; Our gripe was that developers seem to completely ignore layering principles once they start coding and introduce cycles, put things in the wrong layer, etc.&amp;nbsp; &lt;strong&gt;A brief recap of layering principles&lt;/strong&gt;:&amp;nbsp; Types in one layer can only access types in the adjacent lower layer.&amp;nbsp; That&amp;rsquo;s it.&amp;nbsp; Types that access types in a layer above are violating layering (or aren&amp;rsquo;t layer) and types that access types in a layer lower than the adjacent lower level (e.g. two layers down) are violating layering.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ve blogged about Visual Studio and layers (and &lt;a href="http://bit.ly/MAXJUp"&gt;validation&lt;/a&gt;) before; but not everyone uses the part of Visual Studio or doesn&amp;rsquo;t have that edition of Visual Studio.&amp;nbsp; I mentioned in our conversation it&amp;rsquo;s fairly easy to write unit tests to make these verifications.&amp;nbsp; I&amp;rsquo;ve written tests like this before, but the assumption was that &amp;ldquo;layers&amp;rdquo; were in different assemblies.&amp;nbsp; The verification for this scenario is quite a bit simpler; so, I thought I&amp;rsquo;d tackle a test that verifies layering within a single assembly where namespaces are the scope of layers.&lt;/p&gt;
&lt;p&gt;My initial code used &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Enumerable.Any&lt;/span&gt; to see if any types from a lower layer not adjacent to the current layer where used in this layer or whether any types from any layers above the current layer where used in this layer.&amp;nbsp; This did the validation, but basically left the dev with a &amp;ldquo;test failed and I&amp;rsquo;m not giving you any details&amp;rdquo; message because we couldn&amp;rsquo;t tell where the violation was and what violated it&amp;mdash;which isn&amp;rsquo;t too friendly.&amp;nbsp; So, I expanded it out to detail &lt;strong&gt;all &lt;/strong&gt;the violations.&amp;nbsp; I came up with a utility method &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;ValidateLayerRelationships&lt;/span&gt; would be used as follows:&lt;/p&gt;
&lt;pre style="line-height:normal;background:white;"&gt;&lt;span&gt;&lt;span&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;pre&gt;&lt;span&gt;public&lt;/span&gt;&amp;nbsp;&lt;span&gt;enum&lt;/span&gt;&amp;nbsp;&lt;span&gt;Layer&lt;/span&gt;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;//&amp;nbsp;Order&amp;nbsp;is&amp;nbsp;important!&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Data,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Domain,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;UI
}
 
[&lt;span&gt;TestMethod&lt;/span&gt;]
&lt;span&gt;public&lt;/span&gt;&amp;nbsp;&lt;span&gt;void&lt;/span&gt;&amp;nbsp;ValidateLayerUsage()
{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;relatedNamespaces&amp;nbsp;=&amp;nbsp;&lt;span&gt;new&lt;/span&gt;[]&amp;nbsp;{&amp;nbsp;&lt;span&gt;&amp;quot;PRI.Data&amp;quot;&lt;/span&gt;,&amp;nbsp;&lt;span&gt;&amp;quot;PRI.Domain&amp;quot;&lt;/span&gt;,&amp;nbsp;&lt;span&gt;&amp;quot;PRI.FrontEnd&amp;quot;&lt;/span&gt;,&amp;nbsp;&lt;span&gt;&amp;quot;PRI.ViewModels&amp;quot;&lt;/span&gt;&amp;nbsp;};
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;levelMap&amp;nbsp;=&amp;nbsp;&lt;span&gt;new&lt;/span&gt;&amp;nbsp;&lt;span&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span&gt;string&lt;/span&gt;,&amp;nbsp;&lt;span&gt;Layer&lt;/span&gt;&amp;gt;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{relatedNamespaces[0],&amp;nbsp;&lt;span&gt;Layer&lt;/span&gt;.Data},
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{relatedNamespaces[1],&amp;nbsp;&lt;span&gt;Layer&lt;/span&gt;.Domain},
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{relatedNamespaces[2],&amp;nbsp;&lt;span&gt;Layer&lt;/span&gt;.UI},
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{relatedNamespaces[3],&amp;nbsp;&lt;span&gt;Layer&lt;/span&gt;.UI},
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;};
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;assemblyFileName&amp;nbsp;=&amp;nbsp;&lt;span&gt;&amp;quot;ClassLibrary.dll&amp;quot;&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;ValidateLayerRelationships(levelMap,&amp;nbsp;assemblyFileName);
}&lt;/pre&gt;
&lt;/pre&gt;
&lt;p&gt;In this example I have two namespaces in one layer (the UI layer) &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;FrontEnd&lt;/span&gt; and &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;ViewModels&lt;/span&gt; and two other layers with just one namespace in each (&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Data&lt;/span&gt; with &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Data&lt;/span&gt; and &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Domain&lt;/span&gt; with &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;Domain&lt;/span&gt;). mostly to show you can have more than one namespace per layer&amp;hellip;&amp;nbsp;&amp;nbsp; We define a layer map, and the filename of the assembly we want to validate and call &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;ValidateLayerRelationships&lt;/span&gt;.&amp;nbsp; &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;ValidateLayerRelationships&lt;/span&gt; is as follows:&lt;/p&gt;
&lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="font-size:12pt;"&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;pre&gt;&lt;span&gt;private&lt;/span&gt;&amp;nbsp;&lt;span&gt;static&lt;/span&gt;&amp;nbsp;&lt;span&gt;void&lt;/span&gt;&amp;nbsp;ValidateLayerRelationships(&lt;span&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span&gt;string&lt;/span&gt;,&amp;nbsp;&lt;span&gt;Layer&lt;/span&gt;&amp;gt;&amp;nbsp;levelMap,&amp;nbsp;&lt;span&gt;string&lt;/span&gt;&amp;nbsp;assemblyFileName)&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;//&amp;nbsp;can&amp;#39;t&amp;nbsp;use&amp;nbsp;ReflectionOnlyLoadFrom&amp;nbsp;because&amp;nbsp;we&amp;nbsp;want&amp;nbsp;to&amp;nbsp;peek&amp;nbsp;at&amp;nbsp;attributes&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;groups&amp;nbsp;=&amp;nbsp;&lt;span&gt;from&lt;/span&gt;&amp;nbsp;t&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;&lt;span&gt;Assembly&lt;/span&gt;.LoadFrom(assemblyFileName).GetTypes()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;where&lt;/span&gt;&amp;nbsp;levelMap.Keys.Contains(t.Namespace)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;group&lt;/span&gt;&amp;nbsp;t&amp;nbsp;&lt;span&gt;by&lt;/span&gt;&amp;nbsp;t.Namespace
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;into&lt;/span&gt;&amp;nbsp;g
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;orderby&lt;/span&gt;&amp;nbsp;levelMap[g.Key]
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;select&lt;/span&gt;&amp;nbsp;g;
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;levelsWithClasses&amp;nbsp;=&amp;nbsp;groups.Count();
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;Assert&lt;/span&gt;.IsTrue(levelsWithClasses&amp;nbsp;&amp;gt;&amp;nbsp;1,&amp;nbsp;&lt;span&gt;&amp;quot;Need&amp;nbsp;more&amp;nbsp;than&amp;nbsp;two&amp;nbsp;layers&amp;nbsp;to&amp;nbsp;validate&amp;nbsp;relationships.&amp;quot;&lt;/span&gt;);
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;errors&amp;nbsp;=&amp;nbsp;&lt;span&gt;new&lt;/span&gt;&amp;nbsp;&lt;span&gt;List&lt;/span&gt;&amp;lt;&lt;span&gt;string&lt;/span&gt;&amp;gt;();
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span&gt;var&lt;/span&gt;&amp;nbsp;g&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;groups){
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;layer&amp;nbsp;=&amp;nbsp;levelMap[g.Key];
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;//&amp;nbsp;verify&amp;nbsp;this&amp;nbsp;level&amp;nbsp;only&amp;nbsp;accesses&amp;nbsp;things&amp;nbsp;from&amp;nbsp;the&amp;nbsp;adjacent&amp;nbsp;lower&amp;nbsp;layer&amp;nbsp;(or&amp;nbsp;layers)&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;offLimitSubsets&amp;nbsp;=&amp;nbsp;&lt;span&gt;from&lt;/span&gt;&amp;nbsp;g1&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;groups&amp;nbsp;&lt;span&gt;where&lt;/span&gt;&amp;nbsp;!&lt;span&gt;new&lt;/span&gt;[]&amp;nbsp;{layer&amp;nbsp;-&amp;nbsp;1,&amp;nbsp;layer}.Contains(levelMap[g1.Key])&amp;nbsp;&lt;span&gt;select&lt;/span&gt;&amp;nbsp;g1;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;offLimitTypes&amp;nbsp;=&amp;nbsp;offLimitSubsets.SelectMany(x&amp;nbsp;=&amp;gt;&amp;nbsp;x).ToList();
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span&gt;Type&lt;/span&gt;&amp;nbsp;t&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;g){
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span&gt;MethodInfo&lt;/span&gt;&amp;nbsp;m&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;t.GetAllMethods()){
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;var&lt;/span&gt;&amp;nbsp;methodBody&amp;nbsp;=&amp;nbsp;m.GetMethodBody();
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;if&lt;/span&gt;&amp;nbsp;(methodBody&amp;nbsp;!=&amp;nbsp;&lt;span&gt;null&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span&gt;LocalVariableInfo&lt;/span&gt;&amp;nbsp;v&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;methodBody
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.LocalVariables
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.Where(v&amp;nbsp;=&amp;gt;&amp;nbsp;offLimitTypes
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.Contains(v.LocalType)))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;errors.Add(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;string&lt;/span&gt;.Format(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;&amp;quot;Method&amp;nbsp;\&amp;quot;&lt;/span&gt;&lt;span&gt;{0}&lt;/span&gt;&lt;span&gt;\&amp;quot;&amp;nbsp;has&amp;nbsp;local&amp;nbsp;variable&amp;nbsp;of&amp;nbsp;type&amp;nbsp;&lt;/span&gt;&lt;span&gt;{1}&lt;/span&gt;&lt;span&gt;&amp;nbsp;from&amp;nbsp;a&amp;nbsp;layer&amp;nbsp;it&amp;nbsp;shouldn&amp;#39;t.&amp;quot;&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;m.Name,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;v.LocalType.FullName));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span&gt;ParameterInfo&lt;/span&gt;&amp;nbsp;p&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;m
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.GetParameters()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.Where(p&amp;nbsp;=&amp;gt;&amp;nbsp;offLimitTypes
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.Contains(p.ParameterType)))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;errors.Add(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;string&lt;/span&gt;.Format(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;&amp;quot;Method&amp;nbsp;\&amp;quot;&lt;/span&gt;&lt;span&gt;{0}&lt;/span&gt;&lt;span&gt;\&amp;quot;&amp;nbsp;parameter&amp;nbsp;&lt;/span&gt;&lt;span&gt;{2}&lt;/span&gt;&lt;span&gt;&amp;nbsp;uses&amp;nbsp;parameter&amp;nbsp;type&amp;nbsp;&lt;/span&gt;&lt;span&gt;{1}&lt;/span&gt;&lt;span&gt;&amp;nbsp;from&amp;nbsp;a&amp;nbsp;layer&amp;nbsp;it&amp;nbsp;shouldn&amp;#39;t.&amp;quot;&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;m.Name,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;p.ParameterType.FullName,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;p.Name));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;if&lt;/span&gt;&amp;nbsp;(offLimitTypes.Contains(m.ReturnType)){
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;errors.Add(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;string&lt;/span&gt;.Format(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;&amp;quot;Method&amp;nbsp;\&amp;quot;&lt;/span&gt;&lt;span&gt;{0}&lt;/span&gt;&lt;span&gt;\&amp;quot;&amp;nbsp;uses&amp;nbsp;return&amp;nbsp;type&amp;nbsp;&lt;/span&gt;&lt;span&gt;{1}&lt;/span&gt;&lt;span&gt;&amp;nbsp;from&amp;nbsp;a&amp;nbsp;layer&amp;nbsp;it&amp;nbsp;shouldn&amp;#39;t.&amp;quot;&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;m.Name,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;m.ReturnType.FullName));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span&gt;PropertyInfo&lt;/span&gt;&amp;nbsp;p&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;t
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.GetAllProperties()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.Where(p&amp;nbsp;=&amp;gt;&amp;nbsp;offLimitTypes.Contains(p.PropertyType)))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;errors.Add(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;string&lt;/span&gt;.Format(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;&amp;quot;Type&amp;nbsp;\&amp;quot;&lt;/span&gt;&lt;span&gt;{0}&lt;/span&gt;&lt;span&gt;\&amp;quot;&amp;nbsp;has&amp;nbsp;a&amp;nbsp;property&amp;nbsp;\&amp;quot;&lt;/span&gt;&lt;span&gt;{1}&lt;/span&gt;&lt;span&gt;\&amp;quot;&amp;nbsp;of&amp;nbsp;type&amp;nbsp;&lt;/span&gt;&lt;span&gt;{2}&lt;/span&gt;&lt;span&gt;&amp;nbsp;from&amp;nbsp;a&amp;nbsp;layer&amp;nbsp;it&amp;nbsp;shouldn&amp;#39;t.&amp;quot;&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;t.FullName,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;p.Name,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;p.PropertyType.FullName));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;foreach&lt;/span&gt;(&lt;span&gt;FieldInfo&lt;/span&gt;&amp;nbsp;f&amp;nbsp;&lt;span&gt;in&lt;/span&gt;&amp;nbsp;t.GetAllFields().Where(f=&amp;gt;offLimitTypes.Contains(f.FieldType)))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;errors.Add(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;string&lt;/span&gt;.Format(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;&amp;quot;Type&amp;nbsp;\&amp;quot;&lt;/span&gt;&lt;span&gt;{0}&lt;/span&gt;&lt;span&gt;\&amp;quot;&amp;nbsp;has&amp;nbsp;a&amp;nbsp;field&amp;nbsp;\&amp;quot;&lt;/span&gt;&lt;span&gt;{1}&lt;/span&gt;&lt;span&gt;\&amp;quot;&amp;nbsp;of&amp;nbsp;type&amp;nbsp;&lt;/span&gt;&lt;span&gt;{2}&lt;/span&gt;&lt;span&gt;&amp;nbsp;from&amp;nbsp;a&amp;nbsp;layer&amp;nbsp;it&amp;nbsp;shouldn&amp;#39;t.&amp;quot;&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;t.FullName,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;f.Name,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;f.FieldType.FullName));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;if&lt;/span&gt;&amp;nbsp;(errors.Count&amp;nbsp;&amp;gt;&amp;nbsp;0)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;Assert&lt;/span&gt;.Fail(&lt;span&gt;String&lt;/span&gt;.Join(&lt;span&gt;Environment&lt;/span&gt;.NewLine,&amp;nbsp;&lt;span&gt;new&lt;/span&gt;[]&amp;nbsp;{&lt;span&gt;&amp;quot;Layering&amp;nbsp;violation.&amp;quot;&lt;/span&gt;}.Concat(errors)));
}&lt;/pre&gt;
&lt;/pre&gt;
&lt;p&gt;This method groups types within a layer, then goes through any layers that layer shouldn&amp;rsquo;t have access to (i.e. any layer that isn&amp;rsquo;t the lower adjacent layer, or &amp;ldquo;layer &amp;ndash; 1, layer&amp;rdquo; where we create &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;offLimitSubsets&lt;/span&gt;).&amp;nbsp; For each type we look at return values, parameter values, fields, properties, and methods for any types they use.&amp;nbsp; If any of those types are one of the off limit types, we add an error to our error collection.&amp;nbsp; At the end, if there&amp;rsquo;s any errors we assert and format a nice message with all the violations.&lt;/p&gt;
&lt;p&gt;This is a helper method that you&amp;rsquo;d use somewhere (maybe a helper static class, within the existing test class, whatever).&lt;/p&gt;
&lt;p&gt;This uses some extension classes to make it a bit more readable, which are here:&lt;/p&gt;
&lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:Consolas;"&gt;&lt;span style="font-size:12pt;"&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;pre&gt;&lt;span&gt;public&lt;/span&gt;&amp;nbsp;&lt;span&gt;static&lt;/span&gt;&amp;nbsp;&lt;span&gt;class&lt;/span&gt;&amp;nbsp;&lt;span&gt;TypeExceptions&lt;/span&gt;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;public&lt;/span&gt;&amp;nbsp;&lt;span&gt;static&lt;/span&gt;&amp;nbsp;&lt;span&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span&gt;MethodInfo&lt;/span&gt;&amp;gt;&amp;nbsp;GetAllMethods(&lt;span&gt;this&lt;/span&gt;&amp;nbsp;&lt;span&gt;Type&lt;/span&gt;&amp;nbsp;type)&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;if&lt;/span&gt;&amp;nbsp;(type&amp;nbsp;==&amp;nbsp;&lt;span&gt;null&lt;/span&gt;)&amp;nbsp;&lt;span&gt;throw&lt;/span&gt;&amp;nbsp;&lt;span&gt;new&lt;/span&gt;&amp;nbsp;&lt;span&gt;ArgumentNullException&lt;/span&gt;(&lt;span&gt;&amp;quot;type&amp;quot;&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;return&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;type.GetMethods(&lt;span&gt;BindingFlags&lt;/span&gt;.Instance&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.NonPublic&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.Static&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.Public).Where(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;m&amp;nbsp;=&amp;gt;&amp;nbsp;!m.GetCustomAttributes(&lt;span&gt;true&lt;/span&gt;).Any(a&amp;nbsp;=&amp;gt;&amp;nbsp;a&amp;nbsp;&lt;span&gt;is&lt;/span&gt;&amp;nbsp;&lt;span&gt;CompilerGeneratedAttribute&lt;/span&gt;));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;public&lt;/span&gt;&amp;nbsp;&lt;span&gt;static&lt;/span&gt;&amp;nbsp;&lt;span&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span&gt;FieldInfo&lt;/span&gt;&amp;gt;&amp;nbsp;GetAllFields(&lt;span&gt;this&lt;/span&gt;&amp;nbsp;&lt;span&gt;Type&lt;/span&gt;&amp;nbsp;type)&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;if&lt;/span&gt;&amp;nbsp;(type&amp;nbsp;==&amp;nbsp;&lt;span&gt;null&lt;/span&gt;)&amp;nbsp;&lt;span&gt;throw&lt;/span&gt;&amp;nbsp;&lt;span&gt;new&lt;/span&gt;&amp;nbsp;&lt;span&gt;ArgumentNullException&lt;/span&gt;(&lt;span&gt;&amp;quot;type&amp;quot;&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;return&lt;/span&gt;&amp;nbsp;type.GetFields(&lt;span&gt;BindingFlags&lt;/span&gt;.Instance&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.NonPublic&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.Static&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.Public)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;.Where(f&amp;nbsp;=&amp;gt;&amp;nbsp;!f.GetCustomAttributes(&lt;span&gt;true&lt;/span&gt;).Any(a&amp;nbsp;=&amp;gt;&amp;nbsp;a&amp;nbsp;&lt;span&gt;is&lt;/span&gt;&amp;nbsp;&lt;span&gt;CompilerGeneratedAttribute&lt;/span&gt;));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;public&lt;/span&gt;&amp;nbsp;&lt;span&gt;static&lt;/span&gt;&amp;nbsp;&lt;span&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span&gt;PropertyInfo&lt;/span&gt;&amp;gt;&amp;nbsp;GetAllProperties(&lt;span&gt;this&lt;/span&gt;&amp;nbsp;&lt;span&gt;Type&lt;/span&gt;&amp;nbsp;type)&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;if&lt;/span&gt;&amp;nbsp;(type&amp;nbsp;==&amp;nbsp;&lt;span&gt;null&lt;/span&gt;)&amp;nbsp;&lt;span&gt;throw&lt;/span&gt;&amp;nbsp;&lt;span&gt;new&lt;/span&gt;&amp;nbsp;&lt;span&gt;ArgumentNullException&lt;/span&gt;(&lt;span&gt;&amp;quot;type&amp;quot;&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span&gt;return&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;type.GetProperties(&lt;span&gt;BindingFlags&lt;/span&gt;.Instance&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.NonPublic&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.Static&amp;nbsp;|&amp;nbsp;&lt;span&gt;BindingFlags&lt;/span&gt;.Public).Where
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;(p&amp;nbsp;=&amp;gt;&amp;nbsp;!p.GetCustomAttributes(&lt;span&gt;true&lt;/span&gt;).Any(a&amp;nbsp;=&amp;gt;&amp;nbsp;a&amp;nbsp;&lt;span&gt;is&lt;/span&gt;&amp;nbsp;&lt;span&gt;CompilerGeneratedAttribute&lt;/span&gt;));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
}
&lt;/pre&gt;
&lt;/pre&gt;
&lt;p&gt;Because the compiler generates fields for auto properties and methods for properties, we want to filter out any compiler-generated stuff (what caused the compiler to generate the code will raise a violation) so we don&amp;rsquo;t get any duplicate violations (and violations the user can&amp;rsquo;t do anything about).&amp;nbsp; (which is what the call to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;GetCustomAttributes&lt;/span&gt; is doing)&lt;/p&gt;
&lt;p&gt;I wasn&amp;rsquo;t expecting this to be that long; so, in future blog entries I&amp;rsquo;ll try to detail some other unit tests that validate or verify specific infrastructural details.&amp;nbsp; If you have any specific details you&amp;rsquo;re interested in, leave a comment.&lt;/p&gt;
&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:4px 0px 4px 0px;"&gt;&lt;iframe src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2012/05/25/automated-testing-isn-t-just-for-business-logic.aspx" scrolling="no" frameborder="0" style="border:none;width:325px;height:80px;"&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:0px 0px 0px 0px;"&gt;
&lt;script type="text/javascript"&gt;&lt;/script&gt;
&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1810302" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Unit+Testing/default.aspx">Unit Testing</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/TDD/default.aspx">TDD</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category></item><item><title>Dispose Pattern and “Set large fields to null”</title><link>http://msmvps.com/blogs/peterritchie/archive/2012/04/26/dispose-pattern-and-set-large-fields-to-null.aspx</link><pubDate>Fri, 27 Apr 2012 02:25:12 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1809240</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1809240</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2012/04/26/dispose-pattern-and-set-large-fields-to-null.aspx#comments</comments><description>&lt;p&gt;I was involved in a short side discussion about “should” fields be set to null in the &lt;font face="Courier New"&gt;Dispose&lt;/font&gt; method(s).&amp;#160; I’m not sure what the impetus of the question was; but, if you read through the &lt;a href="http://bit.ly/I8Xf3R"&gt;dispose pattern MSDN documentation&lt;/a&gt; (in most versions I believe) there’s a comment &lt;span&gt;&lt;font face="Consolas"&gt;&lt;font style="font-size:8.4pt;" color="#008000"&gt;// Set large fields to null. &lt;/font&gt;&lt;/font&gt;&lt;/span&gt;in the implementation of the virtual &lt;font face="Courier New"&gt;Dispose&lt;/font&gt; method within the &lt;font face="Courier New"&gt;if(!disposed)&lt;/font&gt; block and after the &lt;font face="Courier New"&gt;if(disposing)&lt;/font&gt; block.&amp;#160; But, that’s the only reference to setting fields to null during dispose.&amp;#160; There’s nothing else that I’ve been able to find in MSDN with regard to setting fields to null.&lt;/p&gt;  &lt;p&gt;At face value, setting a field to null means that the referenced object is now unrooted from the class that owns the field and, if that was the last root of that reference, the Garbage Collector (GC) is now free to release the memory used by the object that was referenced by that field.&amp;#160; Although advanced, this seems all very academic because the amount of time between unrooting the reference and the return from &lt;font face="Courier New"&gt;Dispose&lt;/font&gt; (and thus the unrooting of the parent object) would seem like a very short amount of time.&amp;#160; Even if the amount of time between these two actions is small, setting a single field to null (i.e. a single assignment) seems like such a minor bit of code to provide no adverse affects.&amp;#160; The prevalent opinion seems to be that the GC “handles” this case and does what is best for you without setting the field to null.&lt;/p&gt;  &lt;p&gt;The GC is pretty smart.&amp;#160; There’s a lot of bright people who have worked on the GC over the years; and it improves every release of .NET.&amp;#160; But, that doesn’t answer the question; is there benefit to setting a field to null in the &lt;font face="Courier New"&gt;Dispose&lt;/font&gt; method?&amp;#160; Considering there isn’t much guidance on the topic; I’d though I’d set aside any faith I have in the GC and throw some science at the problem: take my theory, create some experiments, make observations, and collect some evidence.&lt;/p&gt;  &lt;p&gt;What I did was to create two classes, identical except that the &lt;font face="Courier New"&gt;Dispose&lt;/font&gt; method doesn’t set a reference field to null.&amp;#160; The classes contain an field that could reference a “large” or “small” object: I would experiment with large objects and small objects and observe the differences.&amp;#160; The following are the classes:&lt;/p&gt;  &lt;pre style="line-height:normal;background:white;"&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;&lt;font style="font-size:7.8pt;"&gt;	&lt;/font&gt;&lt;/font&gt;&lt;font style="font-size:7.8pt;"&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;First&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; : &lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;IDisposable&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;/font&gt;&lt;font style="font-size:7.8pt;"&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; {
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;[] arr = &lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;new&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;[&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Constants&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;.ArraySize];
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;[] GetArray() {
			&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;return&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; arr;
		}
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;void&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; Dispose() {
			arr = &lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;null&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;;
		}
	}
 
	&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Second&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; : &lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;IDisposable&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; {
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;[] arr = &lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;new&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;[&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Constants&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;.ArraySize];
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;[] GetArray() {
			&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;return&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font style="font-size:7.8pt;"&gt;&lt;font color="#000000"&gt; arr;
		}
 
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;void&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; Dispose() {
		}
	}
&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/pre&gt;

&lt;p&gt;I would vary &lt;font face="Courier New"&gt;Constants.ArraySize&lt;/font&gt; constant to make the &lt;font face="Courier New"&gt;arr&lt;/font&gt; reference a “large” object or a “small” object.&amp;#160; I then created a loop that created several thousand instances of one of these classes then forced a garbage collection at the end; keeping track of the start time and the end time via &lt;font face="Courier New"&gt;Stopwatch&lt;/font&gt;:&lt;/p&gt;

&lt;pre style="line-height:normal;background:white;"&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;&lt;font style="font-size:7.8pt;"&gt;	&lt;/font&gt;&lt;/font&gt;&lt;font style="font-size:7.8pt;"&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Program&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;/font&gt;&lt;font style="font-size:7.8pt;"&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; {
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;private&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;const&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; Iterations = 10000;
 
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;static&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;void&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; Main(&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;[] args)
		{
			&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; stopwatch = &lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Stopwatch&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;.StartNew();
			&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;for&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; (&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; i = 0; i &amp;lt; Iterations; ++i)
			{
				&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; (&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; f = &lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;new&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;First&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;())
				{
					ConsumeValue(f.GetArray().Length);
				}
			}
			&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;GC&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;.Collect();
			stopwatch.Stop();
			&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Trace&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;.WriteLine(&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;String&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;.Format(&lt;/font&gt;&lt;span&gt;&lt;font color="#a31515"&gt;&amp;quot;&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#3cb371"&gt;{0}&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#a31515"&gt;&amp;#160;&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#3cb371"&gt;{1}&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#a31515"&gt;&amp;quot;&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;, stopwatch.Elapsed, stopwatch.ElapsedTicks));
			stopwatch = &lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Stopwatch&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;.StartNew();
			&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;for&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; (&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt; i = 0; i &amp;lt; Iterations; ++i)
			{
				&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; (&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; s = &lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;new&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Second&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;())
				{
					ConsumeValue(s.GetArray().Length);
				}
			}
			&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;GC&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font color="#000000"&gt;.Collect();
			stopwatch.Stop();
			&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;Trace&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;.WriteLine(&lt;/font&gt;&lt;span&gt;&lt;font color="#2b91af"&gt;String&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;.Format(&lt;/font&gt;&lt;span&gt;&lt;font color="#a31515"&gt;&amp;quot;&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#3cb371"&gt;{0}&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#a31515"&gt;&amp;#160;&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#3cb371"&gt;{1}&lt;/font&gt;&lt;/span&gt;&lt;span&gt;&lt;font color="#a31515"&gt;&amp;quot;&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;&lt;font style="font-size:7.8pt;"&gt;&lt;font color="#000000"&gt;, stopwatch.Elapsed, stopwatch.ElapsedTicks));
		}
 
		&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;static&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt;&amp;#160;&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;void&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; ConsumeValue(&lt;/font&gt;&lt;span&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/span&gt;&lt;font color="#000000"&gt; x) {
		}
	}&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/pre&gt;

&lt;p&gt;I wanted to make sure instanced got optimized away so the &lt;font face="Courier New"&gt;GetArray&lt;/font&gt; method makes sure the &lt;font face="Courier New"&gt;arr&lt;/font&gt; field sticks around and the &lt;font face="Courier New"&gt;ConsumeValue&lt;/font&gt; makes sure the &lt;font face="Courier New"&gt;First&lt;/font&gt;/&lt;font face="Courier New"&gt;Second&lt;/font&gt; instances stick around (more a knit-picker circumvention measure :).&amp;#160; Results are the 2nd result from running the application 2 times.&lt;/p&gt;

&lt;p&gt;As it turns out, the results were very interesting (at least to me :).&amp;#160; The results are as follows:&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 85000 Debug: yes Elapsed time: 00:00:00.0759408 Ticks: 170186.
  &lt;br /&gt;Iterations: 10000 ArraySize: 85000 Debug: yes Elapsed time: 00:00:00.7449450 Ticks: 1669448.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 85000 Debug: no Elapsed time: 00:00:00.0714526 Ticks: 160128.
  &lt;br /&gt;Iterations: 10000 ArraySize: 85000 Debug: no Elapsed time: 00:00:00.0753187 Ticks: 168792.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 1 Debug: yes Elapsed time: 00:00:00.0009410 Ticks: 2109.
  &lt;br /&gt;Iterations: 10000 ArraySize: 1 Debug: yes Elapsed time: 00:00:00.0007179 Ticks: 1609.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 1 Debug: no Elapsed time: 00:00:00.0005225 Ticks: 1171.
  &lt;br /&gt;Iterations: 10000 ArraySize: 1 Debug: no Elapsed time: 00:00:00.0003908 Ticks: 876.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 1000 Debug: yes Elapsed time: 00:00:00.0088454 Ticks: 19823.
  &lt;br /&gt;Iterations: 10000 ArraySize: 1000 Debug: yes Elapsed time: 00:00:00.0062082 Ticks: 13913.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 1000 Debug: no Elapsed time: 00:00:00.0096442 Ticks: 21613.
  &lt;br /&gt;Iterations: 10000 ArraySize: 1000 Debug: no Elapsed time: 00:00:00.0058977 Ticks: 13217.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 10000 Debug: yes Elapsed time: 00:00:00.0527439 Ticks: 118201.
  &lt;br /&gt;Iterations: 10000 ArraySize: 10000 Debug: yes Elapsed time: 00:00:00.0528719 Ticks: 118488.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 10000 Debug: no Elapsed time: 00:00:00.0478136 Ticks: 107152.
  &lt;br /&gt;Iterations: 10000 ArraySize: 10000 Debug: no Elapsed time: 00:00:00.0524012 Ticks: 117433.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 40000 Debug: yes Elapsed time: 00:00:00.0491652 Ticks: 110181.
  &lt;br /&gt;Iterations: 10000 ArraySize: 40000 Debug: yes Elapsed time: 00:00:00.3580011 Ticks: 802293.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 40000 Debug: no Elapsed time: 00:00:00.0467649 Ticks: 104802.
  &lt;br /&gt;Iterations: 10000 ArraySize: 40000 Debug: no Elapsed time: 00:00:00.0487685 Ticks: 109292.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 30000 Debug: yes Elapsed time: 00:00:00.0446106 Ticks: 99974.
  &lt;br /&gt;Iterations: 10000 ArraySize: 30000 Debug: yes Elapsed time: 00:00:00.2748007 Ticks: 615838.&lt;/p&gt;

&lt;p&gt;Iterations: 10000 ArraySize: 30000 Debug: no Elapsed time: 00:00:00.0411109 Ticks: 92131.
  &lt;br /&gt;Iterations: 10000 ArraySize: 30000 Debug: no Elapsed time: 00:00:00.0381225 Ticks: 85434.

  &lt;br /&gt;&lt;/p&gt;

&lt;p&gt;For the most part, results in debug mode are meaningless.&amp;#160; There’s no point in making design/coding decisions based on perceived benefits in debug mode; so, I don’t the results other than to document them above.&lt;/p&gt;

&lt;p&gt;The numbers could go either way, if we look at percentages; release mode, setting a field to null seems to be slower 50% of the time and faster 50% of the time.&amp;#160; When setting a field to null is faster it’s insignificantly faster (5.41%, 9.59%, and 4.28% faster) when it’s slower it’s insignificantly slower but more slow than it is fast (133.68%, 163.52%, and 107.84% slower).&amp;#160; Neither seems to make a whole lot of difference (like 10281 ticks over 10000 iterations in the biggest difference for about 1 tick per iteration—1000 byte array at 10000 iterations).&amp;#160; If we look at just the time values, we start to see that setting a field starts to approach being faster (when it’s slower it’s slower by 295, 8396, and 6697 ticks; when it’s faster it’s faster by 8664, 10281, 4490).&amp;#160; Oddly though, setting “large” fields to null isn’t the biggest of faster setting field to null values.&amp;#160; But, of course, I don’t know what the documentation means by “large”; it could be large-heap objects or some other arbitrary size.&lt;/p&gt;

&lt;p&gt;Of course there’s other variables that could affect things here that I haven’t accounted for (server GC, client GC, GC not occurring at specific time, better sample size, better sample range, etc.); so, take the results with a grain of salt.&lt;/p&gt;

&lt;p&gt;What should you do with this evidence?&amp;#160; It’s up to you.&amp;#160; I suggest not taking it as gospel and making a decision that is best for you own code based on experimentation and gathered metrics in the circumstances unique to your application and its usage..&amp;#160; i.e. setting a field to null in Dispose is neither bad nor good in the general case.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:4px 0px 4px 0px;"&gt;&lt;iframe src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2012/04/26/dispose-pattern-and-set-large-fields-to-null.aspx" scrolling="no" frameborder="0" style="border:none;width:325px;height:80px;"&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:0px 0px 0px 0px;"&gt;
&lt;script type="text/javascript"&gt;
  (function() {
    var po = document.createElement(&amp;#39;script&amp;#39;); po.type = &amp;#39;text/javascript&amp;#39;; po.async = true;
    po.src = &amp;#39;https://apis.google.com/js/plusone.js&amp;#39;;
    var s = document.getElementsByTagName(&amp;#39;script&amp;#39;)[0]; s.parentNode.insertBefore(po, s);
  })();
&lt;/script&gt;&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1809240" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Pontification/default.aspx">Pontification</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+4.0/default.aspx">.NET 4.0</category></item><item><title>If You’re Using “#if DEBUG”, You’re Doing it Wrong</title><link>http://msmvps.com/blogs/peterritchie/archive/2011/11/24/if-you-re-using-if-debug-you-re-doing-it-wrong.aspx</link><pubDate>Thu, 24 Nov 2011 14:50:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1802873</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>13</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1802873</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2011/11/24/if-you-re-using-if-debug-you-re-doing-it-wrong.aspx#comments</comments><description>&lt;p&gt;I was going through some legacy code the other day, refactoring it all over the place and I ran into many blocks of code wrapped in “#if DEBUG”.&amp;#160; Of course, after a bit of refactoring in a RELEASE configuration these blocks of code were quickly out of date (and by out of date, I mean no longer compiling).&amp;#160; A huge PITA.&lt;/p&gt;  &lt;p&gt;For example, take the following code:&lt;/p&gt;  &lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;	&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;MyCommand&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt; DateAndTimeOfTransaction;
	}
 
	&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Test&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;	{
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/span&gt;
&lt;span style="color:#000000;"&gt;		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; ProcessCommand(&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;MyCommand&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt; myCommand)
		{
&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;#if&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt; DEBUG
&lt;/span&gt;&lt;span&gt;&lt;span style="color:#808080;"&gt;			if (myCommand.DateAndTimeOfTransaction &amp;gt; DateTime.Now)&lt;/span&gt;&lt;/span&gt;
&lt;span&gt;&lt;span style="color:#808080;"&gt;				throw new InvalidOperationException(&amp;quot;DateTime expected to be in the past&amp;quot;);&lt;/span&gt;&lt;/span&gt;
&lt;span&gt;&lt;span style="color:#0000ff;"&gt;#endif&lt;/span&gt;&lt;/span&gt;
&lt;span style="color:#000000;"&gt;			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;// do more stuff with myCommand...&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;		}
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;span style="color:#000000;"&gt;&lt;span style="font-size:x-small;"&gt;	}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;If, while my active configuration is RELEASE, I rename-refactor &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;DateAndTimeOfTransaction&lt;/span&gt; to &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;TransactionDateTime&lt;/span&gt; then the block of code in the #if DEBUG is now invalid—&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;DateAndTimeOfTransaction&lt;/span&gt; will not be renamed within this block.&amp;#160; I will now get compile errors if I switch to DEBUG configuration (or worse still, if I check in an my continuous integration environment does a debug build).&lt;/p&gt;

&lt;p&gt;I would have run into the same problem had I been in a DEBUG configuration with all the “&lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;#if RELEASE&lt;/span&gt;” blocks.&amp;#160; Yes, I could create a configuration and define DEBUG &lt;strong&gt;and&lt;/strong&gt; RELEASE and do my work in there.&amp;#160; Yeah, no, not going down that twisted path… i.e. try doing it without manually adding a conditional compilation symbol.&lt;/p&gt;

&lt;p&gt;I got to thinking about a better way.&amp;#160; It dawned on me that &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;#if&lt;/span&gt; blocks are effectively comments in other configurations (assuming DEBUG or RELEASE; but true with any symbol) and that &lt;a href="http://bit.ly/vDJekK"&gt;comments are apologies&lt;/a&gt;, and it quickly became clear to me how to fix this.&lt;/p&gt;

&lt;p&gt;Enter Extract Method refactoring and Conditional Methods.&amp;#160; If you’ve been living under a rock or have simply forgotten, there exists a type in the BCL: &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;System.Diagnostics.ConditionalAttribute&lt;/span&gt;.&amp;#160; You put this attribute on methods &lt;span style="text-decoration:line-through;"&gt;that&lt;/span&gt;[whose calls] may or may not be included in the resulting binary (IL).&amp;#160; But, they are still compiled (and thus syntax checked).&amp;#160; So, if I followed the basic tenet for &lt;a href="http://bit.ly/47Ld1d"&gt;code comment smells&lt;/a&gt; and performed an Extract Method refactoring and applied the &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;ConditionalAttribute&lt;/span&gt; to the resulting method, I’d end up with something like this:&lt;/p&gt;

&lt;pre style="line-height:normal;background:white;"&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;/span&gt;
&lt;span style="color:#000000;"&gt;		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; ProcessCommand(&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;MyCommand&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt; myCommand)
		{
			CheckMyCommandPreconditions(myCommand);
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#008000;"&gt;// do more stuff with myCommand...&lt;/span&gt;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;		}
 
		[&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;Conditional&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;(&lt;/span&gt;&lt;span&gt;&lt;span style="color:#a31515;"&gt;&amp;quot;DEBUG&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;)]
		&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; CheckMyCommandPreconditions(&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;MyCommand&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt; myCommand)
		{
			&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt; (myCommand.DateAndTimeOfTransaction &amp;gt; &lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:consolas;"&gt;&lt;span style="font-size:x-small;"&gt;&lt;span style="color:#000000;"&gt;.Now)
				&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;throw&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#0000ff;"&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&amp;#160;&lt;/span&gt;&lt;span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;(&lt;/span&gt;&lt;span&gt;&lt;span style="color:#a31515;"&gt;&amp;quot;DateTime expected to be in the past&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="color:#000000;"&gt;&lt;span style="font-size:x-small;"&gt;);
		}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Now, if I perform a rename refactoring on &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;MyCommand.DateAndTimeOfTransaction&lt;/span&gt;, &lt;strong&gt;all&lt;/strong&gt; usages of &lt;span style="font-family:&amp;#39;Courier New&amp;#39;;"&gt;DateAndTimeOfTransaction&lt;/span&gt; get renamed and I no longer introduce compile errors.&lt;/p&gt;

&lt;h3&gt;Code Contracts&lt;/h3&gt;

&lt;p&gt;If you look closely at the name I chose for the extracted method you’ll notice that what this DEBUG code is actually doing is asserting method preconditions.&amp;#160; This type of thing is actually supported in &lt;a href="http://bit.ly/s23uAU"&gt;Code Contracts&lt;/a&gt;.&amp;#160; Code Contracts implement a concept called &lt;a href="http://bit.ly/szEmTc"&gt;Design by Contract&lt;/a&gt; (DbC).&amp;#160; One benefit to DbC is that these checks are effectively proved at compile time so there’s no reason to perform this check at runtime or &lt;a href="http://bit.ly/tYnSGC"&gt;even write unit tests to check them&lt;/a&gt; because code to violate them becomes a “compile error” with Code Contracts.&amp;#160; But, for my example I didn’t use DbC despite potentially being a better way of implementing this particular code.&lt;/p&gt;

&lt;p&gt;Anyone know what we call a refactoring that introduces unwanted side-effects like compile errors?&lt;/p&gt;

&lt;p&gt;[UPDATE: small correction to the description of conditional methods and what does/doesn&amp;#39;t get generated to IL based on comment from Motti Shaked]&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="margin:0px;padding:4px 0px 4px 0px;"&gt;&lt;iframe src="http://www.facebook.com/widgets/like.php?href=http://msmvps.com/blogs/peterritchie/archive/2011/11/24/if-you-re-using-if-debug-you-re-doing-it-wrong.aspx" scrolling="no" frameborder="0" style="border:none;width:130px;height:80px;"&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1802873" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Principles/default.aspx">Software Development Principles</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DbC/default.aspx">DbC</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Code+Contracts/default.aspx">Code Contracts</category></item><item><title>Windows 8, What Does It Mean to Me?</title><link>http://msmvps.com/blogs/peterritchie/archive/2011/09/19/windows-8-what-does-it-mean-to-me.aspx</link><pubDate>Tue, 20 Sep 2011 00:07:14 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1799870</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1799870</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2011/09/19/windows-8-what-does-it-mean-to-me.aspx#comments</comments><description>&lt;p&gt;Well, unless you’ve been hiding under a rock, you’ve probably heard about Microsoft Build conference that happened in Anaheim last week.&amp;#160; It was during this conference that Microsoft finally released details about the successor to Windows 7.&amp;#160; This event is solely developer-focused and, in my opinion, tablet-specific.&amp;#160; It went into a lot of detail about the added APIs and usability changes in Windows 8 to better support tablet and touch-based computers.&lt;/p&gt;  &lt;p&gt;First off, the new touch-first usability changes are called “Metro” and applications written for touch are called “Metro-style apps”.&lt;/p&gt;  &lt;p&gt;The term “touch-first” is used because it’s not touch-only.&amp;#160; Metro will work fine with a mouse and a keyboard; but the user experience is obviously designed for a multi-touch device and that you can “get by” adequately with a mouse and a keyboard.&amp;#160; This was done for various reasons, one being that touch isn’t good for entering reams of text and that you want to dock your tablet and use a keyboard and mouse when you want to do something that would be better served by a keyboard or a mouse.&amp;#160; e.g. tablet/touch-based UX is better for consuming information, whereas keyboard is better for producing information.&lt;/p&gt;  &lt;p&gt;So, with all the focus was on tablet and touch, does that mean Windows 8 is all about Metro?&amp;#160; The focus of the conference was to show off (likely in answer to other vendors producing tablet-based hardware and systems) tablet- and touch-based user experiences.&amp;#160; In fact, paying attendees received a custom-made Samsung tablet computer with a version of Windows 8 (called Developer Preview) and the next version of Visual Studio (called Dev11, for now) pre-installed.&amp;#160; This puts the focus of Developer Preview almost solely on touch.&amp;#160; But, does this mean that mouse/keyboard was ignored or that we need a touch screen on our computers to be able to use Windows 8 when it is released?&amp;#160; No, of course not.&amp;#160; Discussing various things with numerous Softies, the message time and time again was that if something isn’t mentioned, or doesn’t have focus, that doesn’t mean it won’t exist in the release version or in the near future.&amp;#160; It was clear that this version of Windows 8 was produced strictly for this event, and since it was effectively deployed on tablet, it had a tablet edition of the OS.&amp;#160; I.e. if you by a desktop without a multi-touch monitor after Windows 8 comes out, the edition of Windows 8 that will be deployed will not likely have Metro on by default.&amp;#160; But, that’s my opinion.&lt;/p&gt;  &lt;p&gt;We now have Metro apps, and they’re XAML-based and very similar to Silverlight.&amp;#160; You initialize the runtime slightly differently and do some other things slightly differently; but if you’re a Silverlight developer you’ll be right at home in Metro.&amp;#160; Does that mean all Windows 8 development is Metro?&amp;#160; Definitely not.&amp;#160; It’s not C++ based and it is still managed code backed by the CLR (they shows using VB and C#; but F# support should be there for RTM).&amp;#160; The CLR backing Metro apps is the same CLR that backs “Desktop” apps written as WinForms (yes, they’re still supporting &lt;em&gt;that&lt;/em&gt;) traditional Silverlight, Console apps, Windows services apps, etc. etc. etc.&lt;/p&gt;  &lt;p&gt;Does this mean Silverlight and .NET is dead?&amp;#160; Well, no; but you could interpret it that way.&amp;#160; Metro apps are driven by a new Windows API called WinRT—which is basically a object-oriented alternative for the Win32 API and removes blocking methods leaving, or replacing them with, asynchronous methods.&amp;#160; This and the CLR that backs it are inherent parts of Windows 8.&amp;#160; So, it’s technically not it’s own product and simply just another part of Windows.&amp;#160; So, you could say that .NET and Silverlight are just bits of Windows 8 and thus no longer exist as “.NET” and “Silverlight”.&amp;#160; Just like Hydra or Terminal Services really doesn’t exist any more because it’s baked right into Windows.&amp;#160; But, that doesn’t mean they don’t exist in this new form.&lt;/p&gt;  &lt;p&gt;Some discussion has occurred as to whether WinRT is truly CLI-compliant because it doesn’t support all the types and methods that .NET does now.&amp;#160; This isn’t true.&amp;#160; We had these same discussions when Silverlight and Windows Phone came out.&amp;#160; WinRT is just another “profile”.&amp;#160; It has a subset .NET API.&amp;#160; Just like how Silverlight doesn’t include classes like System.Windows.Forms.Form and Windows Phone doesn’t include classes like System.Windows.Browser.HtmlDocument.&amp;#160; The depth of the .NET classes that are available to &lt;em&gt;WinRT&lt;/em&gt; developers is restricted, just restricted differently than Silverlight and Windows Phone.&lt;/p&gt;  &lt;p&gt;Just how restricted is the WinRT profile?&amp;#160; Well, that remains to be seen at this point; but, from the looks of it it is minimally CLI compliant.&amp;#160; This means it doesn’t include things like the reflection namespaces.&amp;#160; WinRT is, after all, for producing touch-based applications that may run on very minimal processors and hardware.&lt;/p&gt;  &lt;p&gt;One thing of note, to finish, is that the theme of WinRT is &lt;em&gt;&lt;strong&gt;asynchronous&lt;/strong&gt;&lt;/em&gt;.&amp;#160; Anything that could take a noticeable amount of time (“blocking”) is not available in the WinRT profile; so, get used to asynchronous programming.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1799870" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+vNext/default.aspx">Visual Studio vNext</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Windows+8/default.aspx">Windows 8</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2011/default.aspx">Visual Studio 2011</category></item><item><title>Developing Windows Services in Visual Studio</title><link>http://msmvps.com/blogs/peterritchie/archive/2011/02/09/developing-windows-services-in-visual-studio.aspx</link><pubDate>Thu, 10 Feb 2011 00:20:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1787928</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1787928</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2011/02/09/developing-windows-services-in-visual-studio.aspx#comments</comments><description>&lt;p&gt;Inevitably distributed systems often need a Windows service or two for certain tasks.&amp;nbsp; The &lt;a href="http://lynk.at/g4l2UA"&gt;creation of a Windows service project and hooking up a project installer&lt;/a&gt; to the service is fairly straightforward; so, I&amp;rsquo;m not going to get into much detail about that stuff.&lt;/p&gt;
&lt;p&gt;The stuff that I find that isn&amp;rsquo;t well understood is how to debug and deploy these services in a development environment.&lt;/p&gt;
&lt;p&gt;First off, debugging.&amp;nbsp; A service is just an executable that is started up by the Windows service manager.&amp;nbsp; From a native application standpoint, it has some entry points in it that the service manager looks for and invokes.&amp;nbsp; From a managed standpoint, it&amp;rsquo;s basically an object that is instantiated and given to &lt;span style="font-family:Courier New;"&gt;System.ServiceProcess.ServiceBase.Run&lt;/span&gt; to get the service running.&amp;nbsp; Of course, the actual execution of service must be in the context of the service manager in order for &lt;span style="font-family:Courier New;"&gt;ServiceBase&lt;/span&gt; to hook into it an tell it what to do.&amp;nbsp; So, simply running a service EXE will spit out a message about not being able to be run from the command-line or a debugger.&amp;nbsp; Ugh, shot down pretty quickly.&lt;/p&gt;
&lt;p&gt;In it&amp;rsquo;s default state, you can simply install the service, start it, and attach a debugger to it (&lt;a href="http://lynk.at/hIZu9w" title="http://lynk.at/hIZu9w"&gt;http://lynk.at/hIZu9w&lt;/a&gt;).&amp;nbsp; This, of course, is a pain if what you want to debug doesn&amp;rsquo;t need to be running in the service manager context.&amp;nbsp; What I&amp;rsquo;ve been doing with services for quite a while now is use a simple trick of deciding in Main whether to call &lt;span style="font-family:Courier New;"&gt;ServiceBase&lt;/span&gt; or call my &lt;span style="font-family:Courier New;"&gt;OnStart&lt;/span&gt; override directly.&amp;nbsp; This is based on tips like &lt;a href="http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx" title="http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx"&gt;http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx&lt;/a&gt; or &lt;a href="http://stackoverflow.com/questions/125964/easier-way-to-start-debugging-a-windows-service-in-c" title="http://stackoverflow.com/questions/125964/easier-way-to-start-debugging-a-windows-service-in-c"&gt;http://stackoverflow.com/questions/125964/easier-way-to-start-debugging-a-windows-service-in-c&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This little trick is basically adding a couple of lines to Main, and a couple of methods to your ServiceBase-derived class and you&amp;rsquo;re done!&amp;nbsp; In your &lt;span style="font-family:Courier New;"&gt;ServiceBase&lt;/span&gt; class, add two methods: InteractiveStart and &lt;span style="font-family:Courier New;"&gt;InteractiveStop&lt;/span&gt;.&amp;nbsp; Each of these methods simply call &lt;span style="font-family:Courier New;"&gt;OnStart&lt;/span&gt; and &lt;span style="font-family:Courier New;"&gt;OnStop&lt;/span&gt;, respectively.&amp;nbsp; &lt;span style="font-family:Courier New;"&gt;OnStart&lt;/span&gt; and &lt;span style="font-family:Courier New;"&gt;OnStop&lt;/span&gt; are protected overrides, so the &lt;span&gt;InteractiveStart&lt;/span&gt; and &lt;span style="font-family:Courier New;"&gt;InteractiveStop&lt;/span&gt; let us gain access to them from outside the class.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="font-family:consolas;background:white;color:black;font-size:13px;"&gt;&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;partial&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;MonitoringService&lt;/span&gt; : &lt;span style="color:#2b91af;"&gt;ServiceBase&lt;/span&gt; {
	&lt;span style="color:blue;"&gt;public&lt;/span&gt; MonitoringService() {
		InitializeComponent();
	}
 
	&lt;span style="color:blue;"&gt;protected&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;override&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;void&lt;/span&gt; OnStart(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args) {
		&lt;span style="color:green;"&gt;// complex multi-threaded code removed for clarity ;)&lt;/span&gt;
	}
 
	&lt;span style="color:blue;"&gt;protected&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;override&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;void&lt;/span&gt; OnStop() {
	}
 
&lt;strong&gt;	&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;void&lt;/span&gt; InteractiveStart() {
		OnStart(&lt;span style="color:blue;"&gt;null&lt;/span&gt;);
	}
 
	&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;void&lt;/span&gt; InteractiveStop() {
		OnStop();
	}&lt;/strong&gt;
}&lt;/pre&gt;
&lt;p&gt;In Main, we simply check &lt;span style="font-family:Courier New;"&gt;Environment.UserInteractive&lt;/span&gt; and call &lt;span style="font-family:Courier New;"&gt;InteractiveStart&lt;/span&gt; and &lt;span style="font-family:Courier New;"&gt;InteractiveStop&lt;/span&gt;.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="font-family:consolas;background:white;color:black;font-size:13px;"&gt;&lt;span style="color:blue;"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;void&lt;/span&gt; Main() {
	&lt;span style="color:blue;"&gt;var&lt;/span&gt; service = &lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;MonitoringService&lt;/span&gt;();
	&lt;span style="color:blue;"&gt;if&lt;/span&gt; (&lt;span style="color:#2b91af;"&gt;Environment&lt;/span&gt;.UserInteractive) {
		service.InteractiveStart();
		&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;service running.&amp;nbsp; Press enter to exit&amp;quot;&lt;/span&gt;);
		&lt;span style="COLOR:#2b91af;"&gt;Console&lt;/span&gt;.ReadLine();		
		service.InteractiveStop();
		&lt;span style="color:blue;"&gt;return&lt;/span&gt;;
	}
	&lt;span style="color:#2b91af;"&gt;ServiceBase&lt;/span&gt;.Run(service);
}&lt;/pre&gt;
&lt;p&gt;Probably a net gain of about seven lines of code.&lt;/p&gt;
&lt;p&gt;To get this to work, you have to change your Windows service project&amp;rsquo;s settings from Windows Application to Console Application.&amp;nbsp; You can now set a breakpoint in your service code and press F5.&lt;/p&gt;
&lt;p&gt;This technique requires none of your service code to change, and you can wire off the code with a simple #if defined(&amp;hellip;) if you like for Release builds.&lt;/p&gt;
&lt;p&gt;Now that life&amp;rsquo;s easier with the ability to easily debug a Windows service; what about where you want to debug something else that uses the service in a running state?&amp;nbsp; You could simply run the EXE so that it runs in our interactive mode and run the other application so it can interact with it.&amp;nbsp; But, sometimes you actually need to be running it as a service (e.g. you need the app to be running in a certain user context).&amp;nbsp; You can use your deployment project and install the service, type in username and password information and then run your other application.&amp;nbsp; But, having to do this more than a couple of times becomes tedious very fast.&amp;nbsp; Luckily, the Framework&amp;rsquo;s &lt;span style="font-family:Courier New;"&gt;InstallUtil&lt;/span&gt; has you covered there.&amp;nbsp; You may be familiar with &lt;span style="font-family:Courier New;"&gt;InstallUtil&lt;/span&gt;&amp;rsquo;s ability to install and uninstall services from the command line (&amp;ldquo;&lt;span style="font-family:Courier New;"&gt;InstallUtil MonitoringService1.exe&lt;/span&gt;&amp;rdquo; to install and &amp;ldquo;&lt;span style="font-family:Courier New;"&gt;InstallUtil /u MonitoringService.exe&lt;/span&gt;&amp;rdquo; to uninstall).&amp;nbsp; But, With the help of &lt;span style="font-family:Courier New;"&gt;ServiceProcessInstaller&lt;/span&gt; added by the designer, &lt;span style="font-family:Courier New;"&gt;InstallUtil&lt;/span&gt; also let&amp;rsquo;s you provide a username and password for when your services is configured in the service process installer for &lt;span style="font-family:Courier New;"&gt;ServiceAccount.User&lt;/span&gt;. It&amp;rsquo;s a simple matter of using &lt;span style="font-family:Courier New;"&gt;username&lt;/span&gt; and &lt;span style="font-family:Courier New;"&gt;password&lt;/span&gt; service parameters.&amp;nbsp; For example:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family:Courier New;"&gt;installutil /username=&amp;quot;.\MonitorServiceAccount&amp;quot; &lt;a&gt;/password=&amp;rdquo;SuperSecretP@55w0rd&lt;/a&gt;&amp;rdquo; MonitoringService.exe&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Try &amp;ldquo;&lt;span style="font-family:Courier New;"&gt;installUtil MyService.exe /?&lt;/span&gt;&amp;rdquo; sometime to see all the options available to you, including password and username, ala &lt;em&gt;Additional Installer Options&lt;/em&gt; at &lt;a href="http://lynk.at/hNsK1R%20" title="http://lynk.at/hNsK1R "&gt;http://lynk.at/hNsK1R &lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Of course, you have to run these from a command line in Administrative mode if you&amp;rsquo;re using Vista/7/2008 and need to make sure the account has rights to&lt;em&gt; run as a service&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;You can even create a batch file to install and start the service.&amp;nbsp; For example:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family:Courier New;"&gt;installutil /username=&amp;quot;.\MonitorServiceAccount&amp;quot; /password=&amp;quot;SuperSecretP@55w0rd&amp;quot; WindowsService1.exe &lt;br /&gt;net start MonitoringService&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Hope this helps!&lt;/p&gt;
&lt;p&gt;[EDIT: added the Console.ReadLine mentioned by Stefan]&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1787928" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2010/default.aspx">Visual Studio 2010</category></item><item><title>Unbind a Visual Studio 2010 Solution from Source Code Control</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/12/11/unbind-a-visual-studio-2010-solution-from-source-code-control.aspx</link><pubDate>Sat, 11 Dec 2010 19:21:51 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1783945</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1783945</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/12/11/unbind-a-visual-studio-2010-solution-from-source-code-control.aspx#comments</comments><description>&lt;p&gt;I was working with a solution that I got from someone else the other day.&amp;#160; When I loaded it up, Visual Studio 2010 informed me that it could not connect to a TFS server at some URL and will open the solution in offline mode (or something to that effect).&amp;#160; Of course, I have no access to this TFS server, so, I’m going to get this message every time I open this solution.&amp;#160; That’s going to get annoying pretty fast.&lt;/p&gt;  &lt;p&gt;So, I had a quick search on the Internet about removing source code control from a Visual Studio 2010.&amp;#160; I found all sorts of information about editing the sln file, removing various sections of an sln file and what-not.&amp;#160; None of this information can from Microsoft.&amp;#160; While in theory doing this would likely do what I wanted, manually editing sln or project files never seems like a good idea.&amp;#160; I don’t know if there are side-effects from this that Visual Studio will telescope into some future version of the sln file and end up causing me problems.&amp;#160; e.g. Visual Studio 201x is released and I try to upgrade this sln file—what if this future version of VS fails or even worse, corrupts my file.&lt;/p&gt;  &lt;p&gt;No, I didn’t want to get chicken blood on my keyboard.&lt;/p&gt;  &lt;p&gt;I was somewhat surprised that my search didn’t immediately show something that wasn’t obvious ritualistic magic; so, I went looking in the File menu at the Source Control entry.&lt;/p&gt;  &lt;p&gt;In there, when my solution was loaded, I simply selected Change Source Control.&amp;#160; As soon as I try to open that dialog VS told me again that it was working offline and wanted to know if I wanted to completely remove the Source Control bindings from my solution.&amp;#160; I simply chose yes and all the SCC bindings were removed from my solution.&lt;/p&gt;  &lt;p&gt;Saving and reloading the SLN file had no source control offline message, and my keyboard is no dirtier than when I started.&lt;/p&gt;  &lt;p&gt;The fact that I couldn’t readily find this with a web search made me think this information would be useful for someone else; so, I’m posting it here in the hopes it helps someone else.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1783945" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2010/default.aspx">Visual Studio 2010</category></item><item><title>Testing Strategies Involving Async Functions</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/11/04/testing-strategies-involving-async-functions.aspx</link><pubDate>Thu, 04 Nov 2010 16:26:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1781600</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1781600</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/11/04/testing-strategies-involving-async-functions.aspx#comments</comments><description>&lt;p&gt;Some things to keep in mind when writing units tests for code that use 
async methods: You&amp;#39;re not trying to test the framework&amp;#39;s &amp;quot;awaitability&amp;quot; 
and you&amp;#39;re not trying to test framework methods that are &amp;quot;awaitable&amp;quot;.&amp;nbsp; 
You want to test your code in certain isolation contexts.&amp;nbsp; One context, 
of course, is independent of asynchronicity--do individual units of code
 that don&amp;#39;t depend on asynchronous invocation &amp;quot;work&amp;quot;...&amp;nbsp; e.g. 
&amp;quot;Task&amp;lt;string&amp;gt; MyMethodAsync()&amp;quot;, you want to have a unit test that 
make sure this method does what it&amp;#39;s supposed to do (one being it 
returns a &amp;quot;valid&amp;quot; Task&amp;lt;string&amp;gt; object, the other being that 
individual side-effects occur, if any).&amp;nbsp; Another context is dependent on
 asynchronicity--do individual units of code that do depend on 
asynchronous invocation (or depend on something being invoked 
asynchronously) &amp;quot;work&amp;quot;.&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
It&amp;#39;s the second context that seems to be the hardest to grasp for most 
people to grasp and action.&amp;nbsp;&amp;nbsp;
Let&amp;#39;s take this example code:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;async&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;void&lt;/span&gt;&amp;nbsp;startButton_Click(&lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;nbsp;sender,&amp;nbsp;&lt;span style="color:#2b91af;"&gt;EventArgs&lt;/span&gt;&amp;nbsp;e)&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;try&lt;/span&gt;&lt;br /&gt;		{&lt;br /&gt;			startButton.Enabled&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;false&lt;/span&gt;;&lt;br /&gt;			&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;webRequest&amp;nbsp;=&amp;nbsp;&lt;span style="color:#2b91af;"&gt;WebRequest&lt;/span&gt;.Create(&lt;span style="color:#a31515;"&gt;&amp;quot;http://google.ca&amp;quot;&lt;/span&gt;);&lt;br /&gt;			&lt;span style="color:blue;"&gt;using&lt;/span&gt;&amp;nbsp;(&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;response&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;await&lt;/span&gt;&amp;nbsp;webRequest.GetResponseAsync())&lt;br /&gt;			&lt;span style="color:blue;"&gt;using&lt;/span&gt;&amp;nbsp;(&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;stream&amp;nbsp;=&amp;nbsp;response.GetResponseStream())&lt;br /&gt;			{&lt;br /&gt;				&lt;span style="color:blue;"&gt;if&lt;/span&gt;&amp;nbsp;(stream&amp;nbsp;==&amp;nbsp;&lt;span style="color:blue;"&gt;null&lt;/span&gt;)&amp;nbsp;&lt;span style="color:blue;"&gt;return&lt;/span&gt;;&lt;br /&gt;				&lt;span style="color:blue;"&gt;using&lt;/span&gt;&amp;nbsp;(&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;reader&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;StreamReader&lt;/span&gt;(stream))&lt;br /&gt;				{&lt;br /&gt;					textBox.Text&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;await&lt;/span&gt;&amp;nbsp;reader.ReadToEndAsync();&lt;br /&gt;				}&lt;br /&gt;			}&lt;br /&gt;		}&lt;br /&gt;		&lt;span style="color:blue;"&gt;finally&lt;/span&gt;&lt;br /&gt;		{&lt;br /&gt;			startButton.Enabled&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;true&lt;/span&gt;;&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;A couple invariants that we want to test might be that the button is disabled during the asynchronous operations and enabled after the asynchronous operations.&amp;nbsp; It&amp;#39;s not immediately obvious what to in order to validate these invariants.&lt;/p&gt;
&lt;p&gt;When the compiler encounters the await operator, it actually goes searching for method that can act upon the type of the object being returned by the method used with the await operator.&amp;nbsp; In our first use of await (on GetResponseAsync()) the return type is Task&amp;lt;T&amp;gt; (Task&amp;lt;WebResponse&amp;gt; specifically, but for our example I&amp;#39;ll use Task&amp;lt;T&amp;gt;).&amp;nbsp; There&amp;#39;s various criteria the computer uses to search for this method, one method is to search for extension methods that match the name and return an &amp;quot;awaiter&amp;quot; type that has the following methods: BeginAwait and EndAwait (more details can be found in the Aync CTP documentation).&amp;nbsp; The compiler doesn&amp;#39;t allow us to inject an awaiter type in the normal run-time dependency injection semantics; but it does allow us to implement an awaiter that does support dependency injection at run-time.&amp;nbsp; To do this I would create an ITaskAwaiter interface like this:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;interface&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;out&lt;/span&gt;&amp;nbsp;T&amp;gt;&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;nbsp;BeginAwait(&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;nbsp;continuation);&lt;br /&gt;		T&amp;nbsp;EndAwait();&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;I then need to create a GetAwaiter(this Task&amp;lt;T&amp;gt;) extension method to return an implementation of this type.&amp;nbsp; The built-in System.Runtime.CompilerServices.TaskAwaiter&amp;lt;T&amp;gt; is public; but, unfortunately it&amp;#39;s constructor (and the ability to pass in a Task&amp;lt;T&amp;gt;) object is internal.&amp;nbsp; So, we can&amp;#39;t simply wrap the built-in awaiter and delegate to it as a default.&amp;nbsp; We actually have to write an awaiter that mimics what the built-in one does.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiter&lt;/span&gt;&amp;lt;T&amp;gt;&amp;nbsp;:&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;T&amp;gt;&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;readonly&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Task&lt;/span&gt;&amp;lt;T&amp;gt;&amp;nbsp;task;&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;TaskAwaiter(&lt;span style="color:#2b91af;"&gt;Task&lt;/span&gt;&amp;lt;T&amp;gt;&amp;nbsp;task)&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;this&lt;/span&gt;.task&amp;nbsp;=&amp;nbsp;task;&lt;br /&gt;		}&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;nbsp;BeginAwait(&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;nbsp;continuation)&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;if&lt;/span&gt;&amp;nbsp;(task.IsCompleted)&amp;nbsp;&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;false&lt;/span&gt;;&lt;br /&gt;			&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;synchronizationContext&amp;nbsp;=&amp;nbsp;&lt;span style="color:#2b91af;"&gt;SynchronizationContext&lt;/span&gt;.Current;&lt;br /&gt;			&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Task&lt;/span&gt;&amp;gt;&amp;nbsp;action&amp;nbsp;=&amp;nbsp;theTask&amp;nbsp;=&amp;gt;&amp;nbsp;&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;	{&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		&lt;span style="color:blue;"&gt;if&lt;/span&gt;&amp;nbsp;(synchronizationContext&amp;nbsp;!=&amp;nbsp;&lt;span style="color:blue;"&gt;null&lt;/span&gt;)&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		{&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;			synchronizationContext.Post(state&amp;nbsp;=&amp;gt;&amp;nbsp;continuation(),&amp;nbsp;&lt;span style="color:blue;"&gt;null&lt;/span&gt;);&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		}&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		&lt;span style="color:blue;"&gt;else&lt;/span&gt;&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		{&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;			continuation();&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		}&lt;br /&gt;			&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;	};&lt;br /&gt; &lt;br /&gt;			task.ContinueWith(action,&amp;nbsp;&lt;span style="color:#2b91af;"&gt;CancellationToken&lt;/span&gt;.None,&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskContinuationOptions&lt;/span&gt;.ExecuteSynchronously,&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskScheduler&lt;/span&gt;.Current);&lt;br /&gt;			&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;true&lt;/span&gt;;&lt;br /&gt;		}&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;T&amp;nbsp;EndAwait()&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;task.Result;&lt;br /&gt;		}&lt;br /&gt;	}&lt;/pre&gt;
&lt;p&gt;This class is given the Task&amp;lt;T&amp;gt; in question, it implements a BeginWait method that sets up an Action delegate to invoke the continuation given to it in a specific synchronization context, then tells the task to use that new action as it&amp;#39;s continuation via a call to ContinueWith.&amp;nbsp; When the task is completed EndAwait will be called and we simply return the result of the task.&lt;/p&gt;
&lt;p&gt;Now, in order to add the ability to inject a customer awaiter, we need to provide the GetAwaiter extension method.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;namespace&lt;/span&gt;&amp;nbsp;PRI.Extensions&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskExtensions&lt;/span&gt;&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;nbsp;GetAwaiter&amp;lt;TResult&amp;gt;(&lt;span style="color:blue;"&gt;this&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Task&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;nbsp;task)&lt;br /&gt;			{&lt;br /&gt;				&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterFactory&lt;/span&gt;&amp;lt;TResult&amp;gt;.CreateTaskAwaiter&amp;nbsp;!=&amp;nbsp;&lt;span style="color:blue;"&gt;null&lt;/span&gt;&lt;br /&gt;					?&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterFactory&lt;/span&gt;&amp;lt;TResult&amp;gt;.CreateTaskAwaiter(task)&amp;nbsp;:&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiter&lt;/span&gt;&amp;lt;TResult&amp;gt;(task);&lt;br /&gt;			}&lt;br /&gt;		}&lt;br /&gt;	}&lt;/pre&gt;
&lt;p&gt;This extension method invokes a factory method delegate to create the ITaskAwaiter&amp;lt;T&amp;gt; object (or simply creates our new default awaiter).&amp;nbsp; This factory method looks like this:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;internal&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterFactory&lt;/span&gt;&amp;lt;TResult&amp;gt;&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Task&lt;/span&gt;&amp;lt;TResult&amp;gt;,&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt;&amp;nbsp;createTaskAwaiter&amp;nbsp;=&amp;nbsp;task&amp;nbsp;=&amp;gt;&lt;br /&gt;		&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;	{&lt;br /&gt;		&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		Current&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiter&lt;/span&gt;&amp;lt;TResult&amp;gt;(task);&lt;br /&gt;		&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;Current;&lt;br /&gt;		&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;	};&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Task&lt;/span&gt;&amp;lt;TResult&amp;gt;,&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt;&amp;nbsp;CreateTaskAwaiter&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;get&lt;/span&gt;&amp;nbsp;{&amp;nbsp;&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;createTaskAwaiter;&amp;nbsp;}&lt;br /&gt;			&lt;span style="color:blue;"&gt;set&lt;/span&gt;&lt;br /&gt;			{&lt;br /&gt;				createTaskAwaiter&amp;nbsp;=&amp;nbsp;task&amp;nbsp;=&amp;gt;&lt;br /&gt;				&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;	{&lt;br /&gt;				&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		Current&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;value&lt;/span&gt;(task);&lt;br /&gt;				&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;		&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;Current;&lt;br /&gt;				&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;	};&lt;br /&gt;			}&lt;br /&gt;		}&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;nbsp;Current&amp;nbsp;{&amp;nbsp;&lt;span style="color:blue;"&gt;get&lt;/span&gt;;&amp;nbsp;&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;set&lt;/span&gt;;&amp;nbsp;}&lt;br /&gt;	}&lt;/pre&gt;
&lt;p&gt;We can override this factory method and give a delegate to code that creates another type of ITaskAwaiter&amp;lt;T&amp;gt; implementation.&amp;nbsp; We also decorate the call to that provided delegate with something that keeps track of the Current awaiter (more on that later).&amp;nbsp; Now, we simply need to add a using statement within our namespace for the compiler to user our GetAwaiter when it compiles an await operator and use our factory.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;namespace&lt;/span&gt;&amp;nbsp;PRI.MainApplication&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;using&lt;/span&gt;&amp;nbsp;PRI.Extensions;&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:green;"&gt;//...&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;We&amp;#39;re now all set to inject a new awaiter and be able to isolate our code from the framework and validate some invariants.&amp;nbsp; In our case, we&amp;#39;d like to check to make sure that the button is disabled during invocation of asynchronous operations and enabled when done.&amp;nbsp; So, we can create a spy awaiter that basically does nothing and sends back a fake or dummy object.&amp;nbsp; In our example we actually have two different types of Task&amp;lt;T&amp;gt; objects being awaited; so, we need to create a couple of awaiter spys.&amp;nbsp; One is generic and one is specific.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;WebResponseTaskAwaiterSpy&lt;/span&gt;&amp;nbsp;:&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;WebResponse&lt;/span&gt;&amp;gt;&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;FakeWebResponse&lt;/span&gt;&amp;nbsp;:&amp;nbsp;&lt;span style="color:#2b91af;"&gt;WebResponse&lt;/span&gt;&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;override&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Stream&lt;/span&gt;&amp;nbsp;GetResponseStream()&lt;br /&gt;			{&lt;br /&gt;				&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;MemoryStream&lt;/span&gt;(System.Text.&lt;span style="color:#2b91af;"&gt;Encoding&lt;/span&gt;.ASCII.GetBytes(&lt;span style="color:#a31515;"&gt;&amp;quot;got&amp;nbsp;some&amp;nbsp;text&amp;quot;&lt;/span&gt;));&lt;br /&gt;			}&lt;br /&gt;		}&lt;br /&gt;		&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;readonly&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;MainForm&lt;/span&gt;&amp;nbsp;form;&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;nbsp;ButtonEnabledState&amp;nbsp;{&amp;nbsp;&lt;span style="color:blue;"&gt;get&lt;/span&gt;;&amp;nbsp;&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;set&lt;/span&gt;;&amp;nbsp;}&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;WebResponseTaskAwaiterSpy(&lt;span style="color:#2b91af;"&gt;MainForm&lt;/span&gt;&amp;nbsp;form)&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;this&lt;/span&gt;.form&amp;nbsp;=&amp;nbsp;form;&lt;br /&gt;		}&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;nbsp;BeginAwait(&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;nbsp;continuation)&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;false&lt;/span&gt;;&lt;br /&gt;		}&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;WebResponse&lt;/span&gt;&amp;nbsp;EndAwait()&lt;br /&gt;		{&lt;br /&gt;			ButtonEnabledState&amp;nbsp;=&amp;nbsp;form.startButton.Enabled;&lt;br /&gt;			&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;FakeWebResponse&lt;/span&gt;();&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt; &lt;br /&gt;	&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterSpy&lt;/span&gt;&amp;lt;T&amp;gt;&amp;nbsp;:&amp;nbsp;&lt;span style="color:#2b91af;"&gt;ITaskAwaiter&lt;/span&gt;&amp;lt;T&amp;gt;&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;readonly&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;MainForm&lt;/span&gt;&amp;nbsp;form;&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;nbsp;ButtonEnabledState&amp;nbsp;{&amp;nbsp;&lt;span style="color:blue;"&gt;get&lt;/span&gt;;&amp;nbsp;&lt;span style="color:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;set&lt;/span&gt;;&amp;nbsp;}&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;TaskAwaiterSpy(&lt;span style="color:#2b91af;"&gt;MainForm&lt;/span&gt;&amp;nbsp;form)&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;this&lt;/span&gt;.form&amp;nbsp;=&amp;nbsp;form;&lt;br /&gt;		}&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;nbsp;BeginAwait(&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;nbsp;continuation)&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;false&lt;/span&gt;;&lt;br /&gt;		}&lt;br /&gt; &lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;T&amp;nbsp;EndAwait()&lt;br /&gt;		{&lt;br /&gt;			ButtonEnabledState&amp;nbsp;=&amp;nbsp;form.startButton.Enabled;&lt;br /&gt;			&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;default&lt;/span&gt;(T);&lt;br /&gt;		}&lt;br /&gt;	}&lt;/pre&gt;
&lt;p&gt;Both classes don&amp;#39;t actually execute the task because we know task execution works and we know it works asynchronously--we&amp;#39;re not trying to test that.&amp;nbsp; The clases return false from BeginAwait to tell the generated code that the asynchronous code &amp;quot;completed&amp;quot; (we lie).&amp;nbsp; The generated code the calls the EndAwait method to get the result of the so-called asynchronous operation.&amp;nbsp; In both cases, we get the state of the button in EndAwait.&amp;nbsp; In the case of the generic spy, we simply return a dummy--the default value for that type parameter.&amp;nbsp; In the case of the WebResponse spy, we can&amp;#39;t send back a dummy because that would be a null value and we&amp;#39;d get NullReferenceEexceptions that would abort our test.&amp;nbsp; So, we create a FakeWebResponse object and send that back that basically creates a canned response stream in memory and sends it back and that will be used in our second await.&lt;/p&gt;
&lt;p&gt;Now, we can write a unit test for startButton_Click method.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:#2b91af;"&gt;MainForm&lt;/span&gt;&amp;nbsp;form&amp;nbsp;=&amp;nbsp;CreateForm();&lt;br /&gt;	&lt;span style="color:#2b91af;"&gt;TaskAwaiterFactory&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;WebResponse&lt;/span&gt;&amp;gt;.CreateTaskAwaiter&amp;nbsp;=&amp;nbsp;task&amp;nbsp;=&amp;gt;&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;WebResponseTaskAwaiterSpy&lt;/span&gt;(form);&lt;br /&gt;	&lt;span style="color:#2b91af;"&gt;TaskAwaiterFactory&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;String&lt;/span&gt;&amp;gt;.CreateTaskAwaiter&amp;nbsp;=&amp;nbsp;task&amp;nbsp;=&amp;gt;&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterSpy&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;String&lt;/span&gt;&amp;gt;(form);&lt;br /&gt; &lt;br /&gt;	form.startButton_Click(&lt;span style="color:blue;"&gt;null&lt;/span&gt;,&amp;nbsp;&lt;span style="color:#2b91af;"&gt;EventArgs&lt;/span&gt;.Empty);&lt;br /&gt; &lt;br /&gt;	&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;spy1&amp;nbsp;=&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterFactory&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;WebResponse&lt;/span&gt;&amp;gt;.Current&amp;nbsp;&lt;span style="color:blue;"&gt;as&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;WebResponseTaskAwaiterSpy&lt;/span&gt;;&lt;br /&gt;	&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;spy2&amp;nbsp;=&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterFactory&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;String&lt;/span&gt;&amp;gt;.Current&amp;nbsp;&lt;span style="color:blue;"&gt;as&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;TaskAwaiterSpy&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;String&lt;/span&gt;&amp;gt;;&lt;br /&gt; &lt;br /&gt;	&lt;span style="color:#2b91af;"&gt;Assert&lt;/span&gt;.IsTrue((spy2&amp;nbsp;!=&amp;nbsp;&lt;span style="color:blue;"&gt;null&lt;/span&gt;&amp;nbsp;&amp;amp;&amp;amp;&amp;nbsp;!spy2.ButtonEnabledState)&amp;nbsp;&amp;amp;&amp;amp;&amp;nbsp;(spy1&amp;nbsp;!=&amp;nbsp;&lt;span style="color:blue;"&gt;null&lt;/span&gt;&amp;nbsp;&amp;amp;&amp;amp;&amp;nbsp;!spy1.ButtonEnabledState));&lt;br /&gt;	&lt;span style="color:#2b91af;"&gt;Assert&lt;/span&gt;.IsTrue(form.startButton.Enabled);&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;This code injects our two types of awaiters (our spies), invokes the method, then checks the spies for the values we&amp;#39;re looking for as well as the current state of our button (we assume the current state at this point is the same state immediately after the asynchronous operation completed) to validate our invariants.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fmsmvps.com%2fblogs%2fpeterritchie%2farchive%2f2010%2f11%2f04%2ftesting-strategies-involving-async-functions.aspx"&gt;&lt;img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%253a%252f%252fmsmvps.com%252fblogs%252fpeterritchie%252farchive%252f2010%252f11%252f04%252ftesting-strategies-involving-async-functions.aspx" alt="kick it on DotNetKicks.com" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1781600" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Unit+Testing/default.aspx">Unit Testing</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/TDD/default.aspx">TDD</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Async+Functions/default.aspx">Async Functions</category></item><item><title>Deep Dive on Closure Pitfalls</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/11/03/deep-dive-on-closure-pitfals.aspx</link><pubDate>Wed, 03 Nov 2010 13:23:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1781490</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1781490</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/11/03/deep-dive-on-closure-pitfals.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ve &lt;a href="http://msmvps.com/blogs/peterritchie/archive/2008/10/27/closure-tip.aspx"&gt;blogged about closures in C# and their pitfalls&lt;/a&gt; before.&amp;nbsp; I keep seeing problems with closures--more now that lambdas expressions and statements (&amp;quot;lambdas&amp;quot;)&amp;nbsp;are becoming more widespread--even with experienced developers. So, I&amp;#39;d thought i&amp;#39;d post about some of the details surrounding where the C# compiler generates closures in the hopes that people will recognize more where they write code that creates a closure and its context.&lt;/p&gt;
&lt;p&gt;The C# language spec does not refer specifically to &amp;quot;closures&amp;quot;, with regard to capturing state for anonymous methods (including lambdas)--it refers to &amp;quot;outer variables&amp;quot; and &amp;quot;captured outer variables&amp;quot;.&amp;nbsp; The captured outer variables for a specific anonymous method are the &amp;quot;closure&amp;quot;.&lt;/p&gt;
&lt;p&gt;The compiler captures the state of variables within the local scope of the anonymous method in a compiler-generated class.&amp;nbsp; The compiler effectively also captures the declaration scope of the state within the closure.&amp;nbsp; If a variable is declared outside the local scope, that is echoed in the use of that closure.&amp;nbsp; If the variable is declared within the local scope, that is captured in use of the closure.&amp;nbsp; So, an anonymous method that uses state (a variable) declared outside the local scope of the anonymous method, the compiler will generate a closure use that closure so that variable is only instantiated once.&amp;nbsp; For example:&amp;nbsp;&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="COLOR:#2b91af;"&gt;ICollection&lt;/span&gt;&amp;lt;&lt;span style="COLOR:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR:blue;"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;&amp;nbsp;Funcs&amp;nbsp;=&amp;nbsp;&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="COLOR:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR:blue;"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;();&amp;nbsp;&lt;br /&gt;	&lt;span style="COLOR:#2b91af;"&gt;String&lt;/span&gt;[]&amp;nbsp;texts&amp;nbsp;=&amp;nbsp;&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;String&lt;/span&gt;[]&amp;nbsp;{&amp;nbsp;&lt;span style="COLOR:#a31515;"&gt;&amp;quot;one&amp;quot;&lt;/span&gt;,&amp;nbsp;&lt;span style="COLOR:#a31515;"&gt;&amp;quot;two&amp;quot;&lt;/span&gt;,&amp;nbsp;&lt;span style="COLOR:#a31515;"&gt;&amp;quot;three&amp;quot;&lt;/span&gt;&amp;nbsp;};&lt;br /&gt;	&lt;span style="COLOR:blue;"&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span style="COLOR:#2b91af;"&gt;String&lt;/span&gt;&amp;nbsp;text&amp;nbsp;&lt;span style="COLOR:blue;"&gt;in&lt;/span&gt;&amp;nbsp;texts)&lt;br /&gt;	{&lt;br /&gt;&lt;span style="background-color:#ffff99;"&gt;		Funcs.Add(&lt;span style="color:blue;"&gt;delegate&lt;/span&gt;&amp;nbsp;{&amp;nbsp;&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;text;&amp;nbsp;});&lt;br /&gt;&lt;/span&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;We have an anonymous method used within the local scope of the body of the foreach loop.&amp;nbsp; The anonymous method uses the &lt;span style="font-family:courier new,courier;"&gt;text&lt;/span&gt; variable declared outside the scope of the foreach loop.&amp;nbsp; The compiler generates a class to contain the state&amp;nbsp;and the code that uses that state&amp;nbsp;(i.e. the anonymous method)--otherwise the highlighted code--and make use of that generated class.&amp;nbsp;&amp;nbsp;For example:&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="color:blue;"&gt;&lt;span style="color:#2b91af;"&gt;Closure &lt;/span&gt;&lt;/span&gt;closure&amp;nbsp;=&amp;nbsp;&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Closure&lt;/span&gt;();&lt;br /&gt;	&lt;span style="color:blue;"&gt;for&lt;/span&gt;&amp;nbsp;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;nbsp;i&amp;nbsp;=&amp;nbsp;0;&amp;nbsp;i&amp;nbsp;&amp;lt;&amp;nbsp;texts.Length;&amp;nbsp;++i)&lt;br /&gt;	{&lt;br /&gt;		closure.text&amp;nbsp;=&amp;nbsp;texts[i];&lt;br /&gt;		Funcs.Add(&lt;span style="color:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt;(closure.Func));&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;The compiler-generated class may look something like this:&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="color:blue;"&gt;internal&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Closure&lt;/span&gt;&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;nbsp;text;&lt;br /&gt;		&lt;span style="color:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;nbsp;Func()&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;text;&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;The compiler instantiates that&amp;nbsp;class outside the generated for loop (because there is no &amp;quot;foreach&amp;quot; loop in .NET&amp;nbsp;IL--what we see here for generated code is a C# view of IL)&amp;nbsp;to match the single declaration of the &lt;span style="font-family:courier new,courier;"&gt;text&lt;/span&gt; variable (as the body of the foreach loop sees it).&amp;nbsp; So, as we can tell from this code, each of these &lt;span style="font-family:courier new,courier;"&gt;Func&lt;/span&gt; delegates are accessing the same variable.&amp;nbsp; So, if we invoked each of those delegate, they would all return &amp;quot;three&amp;quot;.&amp;nbsp; While the code &lt;em&gt;looks&lt;/em&gt; like each &lt;span style="font-family:courier new,courier;"&gt;Func&lt;/span&gt; delegate is dealing with a different value (&amp;quot;one&amp;quot;, then &amp;quot;two&amp;quot;, then &amp;quot;three&amp;quot;); it&amp;#39;s not and you&amp;#39;ve probably got a logic error with this code.&lt;/p&gt;
&lt;p&gt;So, as I pointed out in a previous post, we get around the problem by bringing the value from the outer scope into the inner scope of the anonymous method.&amp;nbsp; For example:&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="color:blue;"&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span style="color:#2b91af;"&gt;String&lt;/span&gt;&amp;nbsp;text&amp;nbsp;&lt;span style="color:blue;"&gt;in&lt;/span&gt;&amp;nbsp;texts)&lt;br /&gt;	{&lt;br /&gt;&lt;span style="background-color:#ffff99;"&gt;		&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;temp&amp;nbsp;=&amp;nbsp;text;&lt;br /&gt;		Funcs.Add(&lt;span style="color:blue;"&gt;delegate&lt;/span&gt;&amp;nbsp;{&amp;nbsp;&lt;span style="color:blue;"&gt;return&lt;/span&gt;&amp;nbsp;temp;&amp;nbsp;});&lt;br /&gt;&lt;/span&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Now, the compiler needs to generate a class to model this local scope--or the highlighted code.&amp;nbsp; This local scope includes the creation of an object and assigning it a specific value.&amp;nbsp; So, what the compiler generates now would be similar to the following:&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="COLOR:blue;"&gt;for&lt;/span&gt;&amp;nbsp;(&lt;span style="COLOR:blue;"&gt;int&lt;/span&gt;&amp;nbsp;i&amp;nbsp;=&amp;nbsp;0;&amp;nbsp;i&amp;nbsp;&amp;lt;&amp;nbsp;texts.Length;&amp;nbsp;++i)&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt;&amp;nbsp;closure&amp;nbsp;=&amp;nbsp;&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt;();&lt;br /&gt;		closure.temp&amp;nbsp;=&amp;nbsp;texts[i];&lt;br /&gt;		Funcs.Add(&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR:blue;"&gt;string&lt;/span&gt;&amp;gt;(closure.Func));&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;With a closure class similar to:&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="COLOR:blue;"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt;&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="COLOR:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:blue;"&gt;string&lt;/span&gt;&amp;nbsp;temp;&lt;br /&gt;		&lt;span style="COLOR:blue;"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:blue;"&gt;string&lt;/span&gt;&amp;nbsp;Func()&lt;br /&gt;		{&lt;br /&gt;			&lt;span style="COLOR:blue;"&gt;return&lt;/span&gt;&amp;nbsp;temp;&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;As we can see here, the compiler is now&amp;nbsp;instantiating a&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt; class once for each iteration of the loop, assigning a specific value to the &lt;span style="font-family:courier new,courier;"&gt;temp&lt;/span&gt; field, then passing a delegate to the &lt;span style="font-family:courier new,courier;"&gt;Func&lt;/span&gt; instance method to a new&lt;span style="font-family:courier new,courier;"&gt; Func&amp;lt;T&amp;gt;&lt;/span&gt; delegate.&amp;nbsp; Now, if we invoke each of our Func delegates we get what we expect &amp;quot;one&amp;quot;, then &amp;quot;two&amp;quot;, then &amp;quot;three&amp;quot;.&lt;/p&gt;
&lt;p&gt;I&amp;#39;ve specifically chosen deferred execution in these examples to separate parallel processing and what&amp;#39;s going on.&amp;nbsp; The same issue occurs when we use anonymous delegates with multiple threads.&amp;nbsp;&amp;nbsp;&amp;nbsp;For example:&amp;nbsp;&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="COLOR:blue;"&gt;var&lt;/span&gt;&amp;nbsp;texts&amp;nbsp;=&amp;nbsp;&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;[]&amp;nbsp;{&amp;nbsp;&lt;span style="COLOR:#a31515;"&gt;&amp;quot;one&amp;quot;&lt;/span&gt;,&amp;nbsp;&lt;span style="COLOR:#a31515;"&gt;&amp;quot;two&amp;quot;&lt;/span&gt;,&amp;nbsp;&lt;span style="COLOR:#a31515;"&gt;&amp;quot;three&amp;quot;&lt;/span&gt;&amp;nbsp;};&lt;br /&gt;	&lt;span style="COLOR:blue;"&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span style="COLOR:blue;"&gt;var&lt;/span&gt;&amp;nbsp;text&amp;nbsp;&lt;span style="COLOR:blue;"&gt;in&lt;/span&gt;&amp;nbsp;texts)&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="COLOR:#2b91af;"&gt;ThreadPool&lt;/span&gt;.QueueUserWorkItem(v&amp;nbsp;=&amp;gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;Trace&lt;/span&gt;.WriteLine(text));&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;This anonymous method (as a lambda) would generate code similar to:&lt;/p&gt;
&lt;pre style="FONT-FAMILY:consolas;"&gt;&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt;&amp;nbsp;closure&amp;nbsp;=&amp;nbsp;&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt;();&lt;br /&gt;	&lt;span style="COLOR:blue;"&gt;for&lt;/span&gt;&amp;nbsp;(&lt;span style="COLOR:blue;"&gt;int&lt;/span&gt;&amp;nbsp;i&amp;nbsp;=&amp;nbsp;0;&amp;nbsp;i&amp;nbsp;&amp;lt;&amp;nbsp;texts.Length;&amp;nbsp;++i)&lt;br /&gt;	{&lt;br /&gt;		closure.text&amp;nbsp;=&amp;nbsp;texts[i];&lt;br /&gt;		&lt;span style="COLOR:#2b91af;"&gt;ThreadPool&lt;/span&gt;.QueueUserWorkItem(&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;WaitCallBack(closure.WaitCallback));&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;/pre&gt;
&lt;p&gt;As you can see, each thread is actually dealing with a single variable (Closure.text). At worst case&amp;nbsp;when each thread runs, it outputs &amp;quot;three&amp;quot;--otherwise it&amp;#39;s undefined what you&amp;#39;ll see.&amp;nbsp; We fix that the same way we did previously by adding a variable into the local scope:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;	&lt;span style="color:blue;"&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;text&amp;nbsp;&lt;span style="color:blue;"&gt;in&lt;/span&gt;&amp;nbsp;texts)&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="color:blue;"&gt;var&lt;/span&gt;&amp;nbsp;temp&amp;nbsp;=&amp;nbsp;text;&lt;br /&gt;		&lt;span style="color:#2b91af;"&gt;ThreadPool&lt;/span&gt;.QueueUserWorkItem(v&amp;nbsp;=&amp;gt;&amp;nbsp;&lt;span style="color:#2b91af;"&gt;Trace&lt;/span&gt;.WriteLine(temp));&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;This then generates something like this:&lt;/p&gt;
&lt;pre style="font-family:consolas;"&gt;&lt;pre style="FONT-FAMILY:consolas;"&gt;	&lt;span style="COLOR:blue;"&gt;for&lt;/span&gt;&amp;nbsp;(&lt;span style="COLOR:blue;"&gt;int&lt;/span&gt;&amp;nbsp;i&amp;nbsp;=&amp;nbsp;0;&amp;nbsp;i&amp;nbsp;&amp;lt;&amp;nbsp;texts.Length;&amp;nbsp;++i)&lt;br /&gt;	{&lt;br /&gt;		&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt;&amp;nbsp;closure&amp;nbsp;=&amp;nbsp;&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt;();&lt;br /&gt;		closure.temp&amp;nbsp;=&amp;nbsp;texts[i];&lt;br /&gt;		&lt;span style="COLOR:#2b91af;"&gt;ThreadPool&lt;/span&gt;.QueueUserWorkItem(&lt;span style="COLOR:blue;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR:#2b91af;"&gt;WaitCallback&lt;/span&gt;(closure.WaitCallback));&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;/pre&gt;
&lt;p&gt;This means each thread is operating on an independent variable (the &lt;span style="font-family:courier new,courier;"&gt;Closure.temp&lt;/span&gt; field of each instance of &lt;span style="COLOR:#2b91af;"&gt;Closure&lt;/span&gt; that was instantiated).&lt;/p&gt;
&lt;p&gt;I hope this makes it more clear what the compiler is doing when you use anonymous methods (including Lambdas).&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fmsmvps.com%2fblogs%2fpeterritchie%2farchive%2f2010%2f11%2f03%2fdeep-dive-on-closure-pitfals.aspx"&gt;&lt;img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%253a%252f%252fmsmvps.com%252fblogs%252fpeterritchie%252farchive%252f2010%252f11%252f03%252fdeep-dive-on-closure-pitfals.aspx" alt="kick it on DotNetKicks.com" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1781490" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+2.0/default.aspx">.NET 2.0</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+3.x/default.aspx">.NET 3.x</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+3.5/default.aspx">.NET 3.5</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_+4/default.aspx">C# 4</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development+Guidance/default.aspx">Software Development Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+4.0/default.aspx">.NET 4.0</category></item><item><title>More on Async Functions</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/10/29/more-on-async-functions.aspx</link><pubDate>Fri, 29 Oct 2010 20:12:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1781064</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1781064</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/10/29/more-on-async-functions.aspx#comments</comments><description>&lt;p&gt;In my last post I showed .Net 1.1 and .NET 2.0 code that performed some asychronous operations.&amp;nbsp; I then showed the new syntax with &amp;quot;async&amp;quot; and &amp;quot;await&amp;quot; that did the same thing.&lt;/p&gt;
&lt;p&gt;But, I didn&amp;#39;t detail what&amp;#39;s really going on in the new syntax.&lt;/p&gt;
&lt;p&gt;If you want to know more about the details of what&amp;#39;s going on, read on.&amp;nbsp; If you just trust me about the previous code, you don&amp;#39;t have to read on :)&lt;/p&gt;
&lt;p&gt;When the Click handler is executed it basically executes everything up to the first &lt;span style="font-family:courier new,courier;"&gt;await &lt;/span&gt;and returns.&amp;nbsp; This allows the UI to be responsive.&amp;nbsp; The compiler generates some code that takes the &lt;span style="font-family:courier new,courier;"&gt;Task&amp;lt;T&amp;gt;&lt;/span&gt; object that is returned from the async method and waits for it.&amp;nbsp; If there is code that needs to execute after the &lt;span style="font-family:courier new,courier;"&gt;await&lt;/span&gt;, then the compiler effectively generates a continuation.&amp;nbsp; With regard to &lt;span style="font-family:courier new,courier;"&gt;Task&amp;lt;T&amp;gt;&lt;/span&gt;, that&amp;#39;s basically a call to &lt;span style="font-family:courier new,courier;"&gt;Task&amp;lt;T&amp;gt;.ContinueWith&lt;/span&gt;.&amp;nbsp; Any other &lt;span style="font-family:courier new,courier;"&gt;await &lt;/span&gt;statements are collected in that continuation and the same thing is done, the continuation is executed up to the first await and returns...&lt;/p&gt;
&lt;p&gt;The underlying architecture knows about synchronization contexts and makes sure &amp;quot;synchronous&amp;quot; code within the &lt;span style="font-family:courier new,courier;"&gt;Click &lt;/span&gt;handler is executed on the UI thread.&amp;nbsp; So, as you saw in the example, we didn&amp;#39;t have to manually deal with marshaling back to the UI thread via &lt;span style="font-family:courier new,courier;"&gt;Control.Invoke().&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;My original example was overly simplistic and didn&amp;#39;t include anything to deal with disposal.&amp;nbsp; To a certain extent I&amp;#39;ve done async functions a disservice because async functions make disposal much, much easier.&amp;nbsp; For example, my .NET 4.0 code would do something like this:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family:courier new,courier;"&gt;private void button_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;button.Enabled = false;&lt;br /&gt;&amp;nbsp;var webRequest = WebRequest.Create(&amp;quot;&lt;/span&gt;&lt;a href="http://google.ca"&gt;&lt;span style="font-family:courier new,courier;"&gt;http://google.ca&lt;/span&gt;&lt;/a&gt;&lt;span style="font-family:courier new,courier;"&gt;&amp;quot;);&lt;br /&gt;&amp;nbsp;webRequest.BeginGetResponse(asyncResult =&amp;gt;&lt;br /&gt;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;var response = webRequest.EndGetResponse(asyncResult);&lt;br /&gt;&amp;nbsp;&amp;nbsp;var stream = response.GetResponseStream();&lt;br /&gt;&amp;nbsp;&amp;nbsp;if (stream != null)&lt;br /&gt;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;var reader = new StreamReader(stream);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;var text = reader.ReadToEnd();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;BeginInvoke((MethodInvoker) (() =&amp;gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;textBox.Text = text;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;button.Enabled = true;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;reader.Dispose();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;stream.Dispose();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;((IDisposable) response).Dispose();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;}));&lt;br /&gt;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;else&lt;br /&gt;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;((IDisposable)response).Dispose();&lt;br /&gt;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;}, null);&lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see, we can&amp;#39;t use the using statement because that assumes the block in which using block resides is run &lt;span style="line-height:115%;font-family:&amp;#39;Arial&amp;#39;,&amp;#39;sans-serif&amp;#39;;color:black;font-size:9pt;mso-fareast-font-family:Calibri;mso-fareast-theme-font:minor-latin;mso-ansi-language:EN-US;mso-fareast-language:EN-US;mso-bidi-language:AR-SA;"&gt;asynchronously&lt;/span&gt;, so we&amp;#39;re forced to manually call &lt;span style="font-family:courier new,courier;"&gt;Dispose &lt;/span&gt;(and in the case of &lt;span style="font-family:courier new,courier;"&gt;WebResponse&lt;/span&gt;, cast to &lt;span style="font-family:courier new,courier;"&gt;IDisposable &lt;/span&gt;first because it explicitly implements &lt;span style="font-family:courier new,courier;"&gt;IDisposable&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;With &lt;span style="font-family:courier new,courier;"&gt;await&lt;/span&gt;, we can write a block of code with bits of it being asynchronous and still use &lt;span style="font-family:courier new,courier;"&gt;using &lt;/span&gt;statements.&amp;nbsp; So, with async functions, our code can now dispose more cleanly; for example:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family:courier new,courier;"&gt;private async void button1_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;try&lt;br /&gt;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;button.Enabled = false;&lt;br /&gt;&amp;nbsp;&amp;nbsp;var webRequest = WebRequest.Create(&amp;quot;&lt;/span&gt;&lt;a href="http://google.ca"&gt;&lt;span style="font-family:courier new,courier;"&gt;http://google.ca&lt;/span&gt;&lt;/a&gt;&lt;span style="font-family:courier new,courier;"&gt;&amp;quot;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;using (var response = await webRequest.GetResponseAsync())&lt;br /&gt;&amp;nbsp;&amp;nbsp;using (var stream = response.GetResponseStream())&lt;br /&gt;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;if (stream == null) return;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;using (var reader = new StreamReader(stream))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;textBox.Text = await reader.ReadToEndAsync();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;finally&lt;br /&gt;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;button.Enabled = true;&lt;br /&gt;&amp;nbsp;}&lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;C# 3&amp;nbsp;and lambda expressions make the act of using asynchronous methods much easier than .NET 1.x; the next version of C# with async functions takes it that final step forward.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1781064" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+vNext/default.aspx">Visual Studio vNext</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Async+Functions/default.aspx">Async Functions</category></item><item><title>A New Asynchronicity Awaits You</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/10/28/a-new-synchronicity-awaits-you.aspx</link><pubDate>Thu, 28 Oct 2010 05:52:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1780932</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1780932</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/10/28/a-new-synchronicity-awaits-you.aspx#comments</comments><description>&lt;p&gt;The languages team at Microsoft have just announced that both VB and C# are giving first-class citizenship to asynchronous operations.&lt;/p&gt;
&lt;p&gt;At long last we can cleanly program for asynchronous operations without cluttering up the code with imperative artefacts relating to how the asynchronous operation is being performed.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s have a quick look at how we had you might perform an asynchronous operation in .NET 1.x:&lt;/p&gt;
&lt;pre&gt;	byte[] readbuffer = new byte[1024];&lt;br /&gt; &lt;br /&gt;	public void Button1_Click()&lt;br /&gt;	{&lt;br /&gt;		WebRequest webRequest = WebRequest.Create(&amp;quot;http://msdn.com&amp;quot;);&lt;br /&gt;		webRequest.BeginGetResponse(new AsyncCallback(BeginGetResponseCallback), webRequest);&lt;br /&gt;	}&lt;br /&gt; &lt;br /&gt;	private void BeginGetResponseCallback(IAsyncResult asyncResult)&lt;br /&gt;	{&lt;br /&gt;		WebRequest webRequest = (WebRequest)asyncResult.AsyncState;&lt;br /&gt;		WebResponse webResponse = webRequest.EndGetResponse(asyncResult);&lt;br /&gt; &lt;br /&gt;		Stream stream = webResponse.GetResponseStream();&lt;br /&gt;		stream.BeginRead(readbuffer, 0, readbuffer.Length, new AsyncCallback(BeginReadCallback), stream);&lt;br /&gt;	}&lt;br /&gt; &lt;br /&gt;	private delegate void TakeString(string text);&lt;br /&gt; &lt;br /&gt;	private void BeginReadCallback(IAsyncResult asyncResult)&lt;br /&gt;	{&lt;br /&gt;		Stream stream = (Stream)asyncResult.AsyncState;&lt;br /&gt;		int read = stream.EndRead(asyncResult);&lt;br /&gt;		this.Invoke(new TakeString(SetTextBoxText), new object[] {Encoding.ASCII.GetString(readbuffer, 0, read);&lt;br /&gt;	}&lt;br /&gt; &lt;br /&gt;	private void SetTextBoxText(String text)&lt;br /&gt;	{&lt;br /&gt;		textBox.Text = text;&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;In .NET 1.x, in order to go get data from a web page in response to a button click, we had to create two methods that acted as callback for the asynchronous get web request and asynchronous read response.&amp;nbsp; As well, we had to create a method to marshal data back to the UI thread via Control.Invoke so that modification of controls (setting of Text property) is done only on the UI thread.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In .NET 2.0 this got much easier.&amp;nbsp; We could use anonymous methods and get rid of our callback methods altogether to get something like this:&lt;/p&gt;
&lt;pre&gt;	public void Button1_Click(object snder, EventArgs e)&lt;br /&gt;	{&lt;br /&gt;		WebRequest webRequest = WebRequest.Create(&amp;quot;http://msdn.com&amp;quot;);&lt;br /&gt;		webRequest.BeginGetResponse(delegate(IAsyncResult asyncResult)&lt;br /&gt;		{&lt;br /&gt;			WebRequest webRequest1 = (WebRequest) asyncResult.AsyncState;&lt;br /&gt;			WebResponse webResponse = webRequest1.EndGetResponse(asyncResult);&lt;br /&gt; &lt;br /&gt;			Stream stream = webResponse.GetResponseStream();&lt;br /&gt;			stream.BeginRead(readbuffer, 0, readbuffer.Length, asyncResult1 =&amp;gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Stream stream1 =&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; (Stream) asyncResult1.AsyncState;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; int read =&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stream1.EndRead(asyncResult1);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.Invoke(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; new TakeString(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; delegate(string text)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; textBox.Text =&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Encoding.ASCII.GetString(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stream1, 0, read);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }));&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }, stream);&lt;br /&gt;		}, webRequest);&lt;br /&gt;	}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;But, the details of anonymous methods and closures really make this code complex and hard to understand.&lt;/p&gt;
&lt;p&gt;In some future version of VB and C#, it will become even easier with the new await/Await and async/Async keywords.&amp;nbsp; In conjunction with the Task Parallel Library, you will now capable of declaring an asynchronous method (&amp;ldquo;asynch&amp;rdquo;) and inform the compiler which part of the method is asynchronous (&amp;ldquo;await&amp;rdquo;).&amp;nbsp; For example:&lt;/p&gt;
&lt;pre&gt;	private async void Button1_Click(object sender, EventArgs e)&lt;br /&gt;	{&lt;br /&gt;		var request = WebRequest.Create(&amp;quot;http://msdn.com&amp;quot;);&lt;br /&gt;		var response = await request.GetResponseAsync();&lt;br /&gt;		var reader = new StreamReader(response.GetResponseStream());&lt;br /&gt; &lt;br /&gt;		textBox.Text = await&lt;br /&gt;		reader.ReadToEndAsync();&lt;br /&gt;	}&lt;br /&gt; &lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Much, much simpler and easier to read.&amp;nbsp; &amp;ldquo;async&amp;rdquo; tells the compiler that a method uses the await keyword.&amp;nbsp; The await keyword tells the compiler that the method being called returns some sort of Task&amp;lt;&amp;gt; object, the type parameter signifying the left-hand-side type of the method call and that the method uses the Task Parallel library to spin up that Task&amp;lt;&amp;gt; object to perform the operation asynchronously.&lt;/p&gt;
&lt;p&gt;As you might imagine, there&amp;rsquo;s a plethora of new methods in the BCL that will now return a Task&amp;lt;&amp;gt; object (and have the postfix of &amp;ldquo;Async&amp;rdquo;) that can be used with the await keyword.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1780932" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+vNext/default.aspx">Visual Studio vNext</category></item><item><title>Visual Studio 2010, Enhance your Jedi Skillz</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/06/15/visual-studio-2010-enhance-your-jedi-skillz.aspx</link><pubDate>Tue, 15 Jun 2010 23:21:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1772089</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1772089</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/06/15/visual-studio-2010-enhance-your-jedi-skillz.aspx#comments</comments><description>&lt;p&gt;I&amp;rsquo;ve blogged about becoming a Jedi in Visual Studio 2008 &lt;a href="http://msmvps.com/blogs/peterritchie/archive/2008/09/02/becoming-a-visual-studio-jedi.aspx"&gt;before&lt;/a&gt;.&amp;nbsp; Being a Jedi in Visual Studio means you focus more on adding value to the software you&amp;rsquo;re working with and less on the process of the IDE you&amp;rsquo;re doing your work in.&lt;/p&gt;
&lt;p&gt;Visual Studio 2010 has some great features to allow you to do just that.&amp;nbsp; So much so, in fact, that I can&amp;rsquo;t possibly do them justice in a single post.&amp;nbsp; I&amp;rsquo;ll start with a few here and continue with a few posts on ways to get Visual Studio 2010 to let you write software faster.&lt;/p&gt;
&lt;p&gt;All of what I&amp;rsquo;ve posted about VS 2010 still applies, like Auto Hide Solution Explorer, Toolbox, etc, single custom toolbar, etc.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Use multiple monitors&lt;/b&gt;.&amp;nbsp; VS 2010 has inherent support for multiple monitors.&amp;nbsp; You could previously get VS to display on multiple monitors; but now the tool windows in VS 2010 can be moved outside the main VS window, and dragged onto another monitor.&amp;nbsp; This is particularly handy (in my opinion) with debugging.&amp;nbsp; You can have your watch window on one monitor, the main editor on another monitor ( and if you&amp;rsquo;re lucky enough to have a 3rd monitor) the application you&amp;rsquo;re debugging on another monitor.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Use Navigate To&lt;/b&gt;.&amp;nbsp; I&amp;rsquo;ve been a user of Resharper for many years.&amp;nbsp; One of it&amp;rsquo;s features is the ability to Go To Declaration&amp;mdash;which allows you to navigate to the declaration of a type (if it&amp;rsquo;s in your solution, metadata if it isn&amp;rsquo;t).&amp;nbsp; Now Visual Studio 2010 has a very similar feature: Navigate To.&amp;nbsp; This feature can be invoked with Ctrl+, and will pre-populate the form with the type at the caret.&amp;nbsp; The form lists all the project files and types within the solution that match the text, including config files, CS files, classes, interfaces, etc.&amp;nbsp; Previously you had to to perform a Find In Files and wade through the false-positives to go right to the declaration of a type.&amp;nbsp; For example, if I press Ctrl+, and type &amp;ldquo;Main&amp;rdquo;, I&amp;rsquo;ll see the following Navigate To form:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/8424.NavigateTo_5F00_485B2D83.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="NavigateTo" alt="NavigateTo" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/8037.NavigateTo_5F00_thumb_5F00_6580D58D.png" border="0" height="426" width="462" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;I can then simply press return to go to the declaration of the Main method.&lt;/p&gt;
&lt;p&gt;If you are a TDD practitioner, &lt;b&gt;switch to Suggestion Mode&lt;/b&gt;.&amp;nbsp; Pressing Ctrl+Alt+Space toggles between Suggestion mode and Completion mode.&amp;nbsp; Completion mode is the IntelliSense mode that was in version 2008 and prior.&amp;nbsp; 2010 has a new Suggestion mode that doesn&amp;rsquo;t auto-complete types when you press space, period, semicolon, etc.&amp;nbsp; They same types show up in the IntelliSense drop-down; but you can still auto-complete the type it suggested by pressing the down arrow then space, period, semicolon, etc.&amp;nbsp; For example, if I&amp;rsquo;m typing test code to test a type named Text, in Completion mode it may auto-complete with &amp;ldquo;TextBox&amp;rdquo; when I press space.&amp;nbsp; In Suggestion mode it will simply accept what I typed when I press space and not auto complete.&amp;nbsp; What&amp;rsquo;s nice in 2010 is that IntelliSense now knows about &amp;ldquo;Text&amp;rdquo; as a type even though I haven&amp;rsquo;t declared it, so when I continue and type &amp;ldquo;text = new T&amp;rdquo;, &amp;ldquo;Text&amp;rdquo; now shows up in the IntelliSense drop-down.&amp;nbsp; I can have it complete it with &amp;ldquo;Text&amp;rdquo; by pressing down-arrow and continue typing.&lt;/p&gt;
&lt;p&gt;Use Call Hierarchy to see what code is calling a particular method.&amp;nbsp; Call Hierarchy is new feature in Visual Studio 2010 that shows you in a tree structure what methods call a particular method as well as what methods a method calls.&amp;nbsp; For example, if I right-click a call to the UnityContainer constructor and select View Call Hierarchy, the Call Hierarchy form is displayed which shows what calls UnityContainer and what UnityContainer calls.&amp;nbsp; For each item in a node, you can expand to see what that method calls and what method calls it.&amp;nbsp; For example, InitializeContainer calls the UnityContainer constructor, if I expand the InitializeContainer entry in the tree I can see what it calls and where it is called from.&amp;nbsp; If I expand it&amp;rsquo;s Calls From &amp;lsquo;InitializeContainer&amp;rsquo; I can see what other methods InitializeContainer calls.&amp;nbsp; For example:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/2555.CallHierarchy_5F00_2BCE15D6.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="CallHierarchy" alt="CallHierarchy" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/8424.CallHierarchy_5F00_thumb_5F00_04B35694.png" border="0" height="287" width="575" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;Since I last blogged on improving your Visual Studio skills, Scott Cate and Steve Andrews have taken up the Visual Studio Tips and Tricks torch from Sara Ford and are hosting &lt;a href="http://vstricks.com"&gt;vstricks.com&lt;/a&gt; and &lt;a href="http://vstips.com"&gt;vstips.com&lt;/a&gt;, respectively.&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fmsmvps.com%2fblogs%2fpeterritchie%2farchive%2f2010%2f06%2f15%2fvisual-studio-2010-enhance-your-jedi-skillz.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fmsmvps.com%2fblogs%2fpeterritchie%2farchive%2f2010%2f06%2f15%2fvisual-studio-2010-enhance-your-jedi-skillz.aspx" alt="kick it on DotNetKicks.com" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1772089" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2010/default.aspx">Visual Studio 2010</category></item><item><title>Using the dynamic Keyword in C# to Improve Object Orientation – A Follow-up</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/05/27/using-the-dynamic-keyword-in-c-to-improve-object-orientation-a-follow-up.aspx</link><pubDate>Thu, 27 May 2010 16:37:30 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1770325</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1770325</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/05/27/using-the-dynamic-keyword-in-c-to-improve-object-orientation-a-follow-up.aspx#comments</comments><description>&lt;p&gt;Based on some feedback, some clarification is warranted with regard to my previous post titled “&lt;a href="http://msmvps.com/blogs/peterritchie/archive/2010/05/24/using-the-dynamic-keyword-in-c-to-improve-object-orientation.aspx"&gt;Using the dynamic Keyword in C# to Improve Object Orientation&lt;/a&gt;”.&lt;/p&gt;  &lt;p&gt;As &lt;a href="http://www.twitter.com/JarekKowalski"&gt;Jarek Kowalski&lt;/a&gt; correctly pointed out, the example code that I provided could have used the &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;Visitor pattern&lt;/a&gt; instead to get the same result.&amp;#160; My impetus for using the dynamic keyword the way I did was slightly different from how I described my example—which was meant to be easier to read.&lt;/p&gt;  &lt;p&gt;I think it’s worthwhile describing the Visitor Pattern.&amp;#160; The Visitor pattern is a pattern used to separate the responsibility of an algorithm from the class that the algorithm should operate upon.&amp;#160; Essentially, a Visitor class is created to contain the algorithm that would be invoked through its Visit method and the classes that the algorithm operates upon some sort of method that accepts a reference to a Visitor object (which would simply invoke the Visit method).&amp;#160; The example that Jarek provided was very similar to:&lt;/p&gt;  &lt;div style="color:black;"&gt;   &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;span style="color:#0000ff;"&gt;interface&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;span style="color:#2b91af;"&gt;IShapeVisitor&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt; Visit(&lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt; square);&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt; Visit(&lt;span style="color:#2b91af;"&gt;Rectangle&lt;/span&gt;&lt;span style="color:#000000;"&gt; square);&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; &lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt; : &lt;span style="color:#2b91af;"&gt;Shape&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;span style="color:#0000ff;"&gt;override&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt; Accept(&lt;span style="color:#2b91af;"&gt;IShapeVisitor&lt;/span&gt;&lt;span style="color:#000000;"&gt; shapeVisitor)&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 			shapeVisitor.Visit(&lt;span style="color:#0000ff;"&gt;this&lt;/span&gt;&lt;span style="color:#000000;"&gt;);&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt;&amp;#160;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And an implementation of IShapeVisitor would be provided like this:&lt;/p&gt;

&lt;div style="color:black;"&gt;
  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;DrawingVisitor&lt;/span&gt;&lt;span style="color:#000000;"&gt;  : IShapeVisitor&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  Visit(Circle circle)&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 			&lt;span style="color:#008000;"&gt;// draw circle here&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  Visit(Rectangle rectangle)&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 			&lt;span style="color:#008000;"&gt;// draw rectangle here&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; &lt;/pre&gt;

  &lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;&lt;span style="color:#000000;"&gt;In our case, the bodies of Visit methods would call a Draw method contained in another class like a View implementation.&amp;#160; For example:&lt;/span&gt; &lt;/span&gt;

                &lt;div style="color:black;"&gt;
                  &lt;div style="color:black;"&gt;
                    &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;class&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;DrawingVisitor&lt;/span&gt;&lt;span style="color:#000000;"&gt;  : &lt;span style="color:#2b91af;"&gt;IShapeVisitor&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;IView&lt;/span&gt;&lt;span style="color:#000000;"&gt;  view;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  DrawingVisitor(&lt;span style="color:#2b91af;"&gt;IView&lt;/span&gt;&lt;span style="color:#000000;"&gt;  view)&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 			&lt;span style="color:#0000ff;"&gt;this&lt;/span&gt;&lt;span style="color:#000000;"&gt;.view = view;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; &lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  Visit(&lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt;  circle)&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 			view.Draw(circle);&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; &lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  Visit(&lt;span style="color:#2b91af;"&gt;Rectangle&lt;/span&gt;&lt;span style="color:#000000;"&gt;  rectangle)&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 			view.Draw(rectangle);&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;

                    &lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
                  &lt;/div&gt;

                  &lt;p&gt;This of course, adds another level of indirection that allows our target (a Shape implementation) to invoke a virtual method that ends up delegating to the Visitor.&amp;#160; An implementation of &lt;a href="http://en.wikipedia.org/wiki/Double_dispatch"&gt;Double Dispatch&lt;/a&gt;.&amp;#160; This allows objects whose type isn’t known until run-time to properly invoke overloaded methods of another type.&lt;/p&gt;

                  &lt;p&gt;As you can see, this is very powerful but adds a bit more complexity.&lt;/p&gt;

                  &lt;p&gt;Now, in my original scenario (before I wrote the example for the post), I was dealing with invoking particular series of static overloads of System.Convert.&amp;#160; Because I was dealing both with a class outside of my control and dealing with static overloads, the Visitor pattern could not be applied.&lt;/p&gt;

                  &lt;p&gt;&lt;/p&gt;
                &lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1770325" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2010/default.aspx">Visual Studio 2010</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+4.0/default.aspx">.NET 4.0</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>Using the dynamic Keyword in C# to Improve Object-Orientation</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/05/24/using-the-dynamic-keyword-in-c-to-improve-object-orientation.aspx</link><pubDate>Mon, 24 May 2010 16:18:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1768867</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1768867</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/05/24/using-the-dynamic-keyword-in-c-to-improve-object-orientation.aspx#comments</comments><description>&lt;p&gt;With polymorphism, object-oriented languages allow &amp;quot;...different data types to be handled using a uniform interface&amp;quot;.&amp;nbsp; Ad-hoc polymorphism is when you declare multiple methods of the same name but differ by the type of an argument.&amp;nbsp; For example: &lt;/p&gt;
&lt;div style="color:black;"&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  Draw(&lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt;  circle)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  Draw(&lt;span style="color:#2b91af;"&gt;Square&lt;/span&gt;&lt;span style="color:#000000;"&gt;  square)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;These are usually referred to as &lt;i&gt;method overloads&lt;/i&gt; or &lt;i&gt;method overloading&lt;/i&gt;.&amp;nbsp; Which Draw method that gets invoked would be decided upon at compile-time based on the type of the parameter passed to it. &lt;/p&gt;
&lt;p&gt;This is great, there are many situations where this is useful; but what about situations where you don&amp;#39;t know the exact type of the object until run-time?&amp;nbsp; Many programmers instinctly lean towards using the GetType method available on all objects in .NET and perform a manual type comparison.&amp;nbsp; For example: &lt;/p&gt;
&lt;div style="color:black;"&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  ProcessShape(&lt;span style="color:#2b91af;"&gt;Shape&lt;/span&gt;&lt;span style="color:#000000;"&gt;  shape)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;&lt;span style="color:#000000;"&gt;  type = shape.GetType();&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;span style="color:#000000;"&gt;  (type == &lt;span style="color:#0000ff;"&gt;typeof&lt;/span&gt;&lt;span style="color:#000000;"&gt; (&lt;span style="color:#2b91af;"&gt;Square&lt;/span&gt;&lt;span style="color:#000000;"&gt; ))&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 		Draw((&lt;span style="color:#2b91af;"&gt;Square&lt;/span&gt;&lt;span style="color:#000000;"&gt; )shape);&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;else&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;span style="color:#000000;"&gt;  (type == &lt;span style="color:#0000ff;"&gt;typeof&lt;/span&gt;&lt;span style="color:#000000;"&gt; (&lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt; ))&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 		Draw((&lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt; )shape);&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;There are other variants of this that make it a little harder to detect (and often gets around static code analysis warnings): &lt;/p&gt;
&lt;div style="color:black;"&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#0000ff;"&gt;public&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt;&lt;span style="color:#000000;"&gt;  ProcessShape(&lt;span style="color:#2b91af;"&gt;Shape&lt;/span&gt;&lt;span style="color:#000000;"&gt;  shape)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#2b91af;"&gt;Square&lt;/span&gt;&lt;span style="color:#000000;"&gt;  square = shape &lt;span style="color:#0000ff;"&gt;as&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;Square&lt;/span&gt;&lt;span style="color:#000000;"&gt; ;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;span style="color:#000000;"&gt;  (square != &lt;span style="color:#0000ff;"&gt;null&lt;/span&gt;&lt;span style="color:#000000;"&gt; )&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 		Draw(square);&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;return&lt;/span&gt;&lt;span style="color:#000000;"&gt; ;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt;  circle = shape &lt;span style="color:#0000ff;"&gt;as&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;Circle&lt;/span&gt;&lt;span style="color:#000000;"&gt; ;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;if&lt;/span&gt;&lt;span style="color:#000000;"&gt;  (circle != &lt;span style="color:#0000ff;"&gt;null&lt;/span&gt;&lt;span style="color:#000000;"&gt; )&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 		Draw(circle);&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 		&lt;span style="color:#0000ff;"&gt;return&lt;/span&gt;&lt;span style="color:#000000;"&gt; ;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;This code is a problem because we lose the benefits of C#s polymorphism (this code is coupled to Circle and Shape, if either is removed, this code would have to be changed and re-tested.&amp;nbsp;&amp;nbsp; If another Shape derivative were added, the code would again have to be changed and re-tested).&amp;nbsp; There are multiple circumstances where this might happen over and above the so-far specious examples above.&amp;nbsp; For example, deserializing an object from a Stream often results in not knowing the exact type of the object that has been deserialized.&amp;nbsp; This is common with type hierarchies.&amp;nbsp; For example: &lt;/p&gt;
&lt;div style="color:black;"&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;Shape&lt;/span&gt;&lt;span style="color:#000000;"&gt;  DeserializeShape(&lt;span style="color:#2b91af;"&gt;Stream&lt;/span&gt;&lt;span style="color:#000000;"&gt;  stream)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#2b91af;"&gt;IFormatter&lt;/span&gt;&lt;span style="color:#000000;"&gt;  formatter = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;BinaryFormatter&lt;/span&gt;&lt;span style="color:#000000;"&gt; ();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;return&lt;/span&gt;&lt;span style="color:#000000;"&gt;  formatter.Deserialize(stream) &lt;span style="color:#0000ff;"&gt;as&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;Shape&lt;/span&gt;&lt;span style="color:#000000;"&gt; ;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;With the above code, we&amp;#39;ve re-hydrated either a Circle of a Square object into a Shape object (and ignored the appropriate checks to make sure a Shape object was loaded).&amp;nbsp; We&amp;#39;re now unable to use all the other polymorphism features of C#: method overloading won&amp;#39;t work, C# will always only use the overload with the Shape argument and generics suffers from the same problem, it will always resolve to the type parameter of type Shape.&amp;nbsp; For example, if we try to call one of our two Draw methods with our re-hydrated Shape object: &lt;/p&gt;
&lt;div style="color:black;"&gt;
&lt;pre style="margin:0em;"&gt; 			Draw(shape);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;br /&gt;...we simply get a CS1502 warning because there is now Draw(Shape shape) method. 
&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;When programmers simply compare types, they&amp;#39;re admitting that polymorphism has been circumvented and they have to resort to introducing the &lt;i&gt;Conditional Complexity&lt;/i&gt; Code Smell or the &lt;i&gt;Switch Statement&lt;/i&gt; Code Smell (C# doesn&amp;#39;t support Type in a switch statement, so some programmers go ahead and create a integer type code--or even worse, use String in the switch statement) &lt;/p&gt;
&lt;p&gt;So, what&amp;#39;s a programmer to do to keep our code object-oriented and use polymorphism? &lt;/p&gt;
&lt;p&gt;Well, if you read the title of this post, you&amp;#39;ve probably figured it out: use the dynamic keyword.&amp;nbsp; The dynamic keyword bypasses static (compile-time) type checking and performs the type-checking dynamically (at run-time).&amp;nbsp; So, for us to use our Draw overloads with our Shape object, we simply assign it to a dynamic object and use that object instead.&amp;nbsp; For example: &lt;/p&gt;
&lt;div style="color:black;"&gt;
&lt;pre style="margin:0em;"&gt; 			&lt;span style="color:#2b91af;"&gt;Shape&lt;/span&gt;&lt;span style="color:#000000;"&gt;  shape = DeserializeShape(stream);&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 			&lt;span style="color:#0000ff;"&gt;dynamic&lt;/span&gt;&lt;span style="color:#000000;"&gt;  dynShape = shape;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 			Draw(dynShape);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Now the runtime will check to see the actual type of dynShape object and invoke the corresponding Draw overload. &lt;/p&gt;
&lt;p&gt;In our example, we&amp;#39;ve used inheritance to derive our two shapes from a single base.&amp;nbsp; But, given our current use of Circle and Square objects, we don&amp;#39;t need them to inherit from the same base class.&amp;nbsp; We could simply view these shapes as an Object when we want to use dynamic.&amp;nbsp; For example: &lt;/p&gt;
&lt;div style="color:black;"&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#0000ff;"&gt;private&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;Object&lt;/span&gt;&lt;span style="color:#000000;"&gt;  DeserializeShape(&lt;span style="color:#2b91af;"&gt;Stream&lt;/span&gt;&lt;span style="color:#000000;"&gt;  stream)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;{&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#2b91af;"&gt;IFormatter&lt;/span&gt;&lt;span style="color:#000000;"&gt;  formatter = &lt;span style="color:#0000ff;"&gt;new&lt;/span&gt;&lt;span style="color:#000000;"&gt;  &lt;span style="color:#2b91af;"&gt;BinaryFormatter&lt;/span&gt;&lt;span style="color:#000000;"&gt; ();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 	&lt;span style="color:#0000ff;"&gt;return&lt;/span&gt;&lt;span style="color:#000000;"&gt;  formatter.Deserialize(stream);&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;span style="color:#000000;"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 			&lt;span style="color:#008000;"&gt;//...&lt;/span&gt;&lt;span style="color:#000000;"&gt; &lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 			&lt;span style="color:#0000ff;"&gt;dynamic&lt;/span&gt;&lt;span style="color:#000000;"&gt;  shape = DeserializeShape(stream);&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; 			Draw(shape);&lt;/pre&gt;
&lt;pre style="margin:0em;"&gt; &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;With the above, we&amp;rsquo;d have the same result without deriving both Circle and Square from Shape.&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fmsmvps.com%2fblogs%2fpeterritchie%2farchive%2f2010%2f05%2f24%2fusing-the-dynamic-keyword-in-c-to-improve-object-orientation.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fmsmvps.com%2fblogs%2fpeterritchie%2farchive%2f2010%2f05%2f24%2fusing-the-dynamic-keyword-in-c-to-improve-object-orientation.aspx" alt="kick it on DotNetKicks.com" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1768867" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+Development/default.aspx">.NET Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Software+Development/default.aspx">Software Development</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Design_2F00_Coding+Guidance/default.aspx">Design/Coding Guidance</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/OOD/default.aspx">OOD</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Visual+Studio+2010/default.aspx">Visual Studio 2010</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/.NET+4.0/default.aspx">.NET 4.0</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Refactoring/default.aspx">Refactoring</category><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/Code+Smells/default.aspx">Code Smells</category></item><item><title>Layers in Visual Studio 2010</title><link>http://msmvps.com/blogs/peterritchie/archive/2010/05/08/layers-in-visual-studio-2010.aspx</link><pubDate>Sat, 08 May 2010 20:32:57 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1765201</guid><dc:creator>PeterRitchie</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/peterritchie/rsscomments.aspx?PostID=1765201</wfw:commentRss><comments>http://msmvps.com/blogs/peterritchie/archive/2010/05/08/layers-in-visual-studio-2010.aspx#comments</comments><description>&lt;p&gt;Visual Studio 2010 has a new featured called Layer Diagrams.&amp;#160; In the Ultimate edition you can create layer diagrams that model the logical layers in your software system.&lt;/p&gt;  &lt;h2&gt;What is a Layer?&lt;/h2&gt;  &lt;p&gt;I’m glad you asked what a layer is.&amp;#160; A layer is a logical grouping of types with similar external assembly dependencies.&amp;#160; Dependencies between layers occur only in one direction from a higher-level layer to a lower-level layer.&amp;#160; I.e. a higher-level layer can use types in a lower-level layer, but not vice versa. A canonical example is the Data Access Layer (or DAL).&amp;#160; The DAL contains all the types that directly use types responsible for data-access.&lt;/p&gt;  &lt;h2&gt;Using the Layer Diagram&lt;/h2&gt;  &lt;p&gt;Within the Layer Diagram user interface, it can be unclear what a layer is.&amp;#160; The Layer Diagram is really just a dependency diagram that allows creation of a logical layer that can be linked to physical artefacts.&lt;/p&gt;  &lt;p&gt;Creating a layer diagram in Visual Studio Ultimate is easy, select New Diagram from the Architecture menu and the Add New Diagram dialog will be displayed.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/4336.vsarchnewdiagram_5F00_404CEEBF.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="vs-arch-new diagram" border="0" alt="vs-arch-new diagram" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/8053.vsarchnewdiagram_5F00_thumb_5F00_46279258.png" width="244" height="67" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In the Add New Diagram dialog, select the Layer Diagram entry and enter the name of the layer diagram file.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/0435.vsaddnewdiagram_5F00_10429D3E.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="vs-add new diagram" border="0" alt="vs-add new diagram" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/1425.vsaddnewdiagram_5F00_thumb_5F00_2DD4783D.png" width="451" height="399" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;If your solution does not currently contain a Modeling project, one will be created automatically when you press OK as indicated by “Create a new modelling project…” in the &lt;strong&gt;Add to modeling project&lt;/strong&gt; combo box.&lt;/p&gt;  &lt;p&gt;Once the modeling project is created and the new layer diagram is added to that project, you will be presented with the Layer Diagram design surface.&amp;#160; You have many options to creating a layer in the diagram, you can use entries in the toolbox to create layers, dependencies, and comments:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/8030.layerdiagramtoolbox_5F00_3989BF6F.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="layer diagram toolbox" border="0" alt="layer diagram toolbox" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/2086.layerdiagramtoolbox_5F00_thumb_5F00_46EFD275.png" width="244" height="169" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Or, you can drag artefacts from the Solution Explorer or the Architecture Explorer to create layers in various ways.&amp;#160; Normal dragging of a single artefact onto the design service creates a new layer with a one-to-one mapping (a “link” in Layer Diagrams) from layer to artefact.&amp;#160; This is especially useful for projects from the solution explorer.&amp;#160; It’s not uncommon for logical layers to be implemented as tiers (or physical assemblies).&amp;#160; Or, you can create a one-to-many mapping from layer to artefacts by normal dragging of artefacts onto the design surface.&amp;#160; This is useful when you’re modeling layers but haven’t modeled them as tiers and multiple layers exist in a single assembly or project.&amp;#160; Via the Architecture Explorer and the Solution Explorer you can link assemblies (projects), types, namespaces, methods, properties, fields, and files to a layer.&lt;/p&gt;  &lt;p&gt;Regardless of how the layer was created on the diagram, you can add links to it by dragging them from the Solution Explorer or Architecture Explorer onto a layer to create a link to it.&amp;#160; Oddly, although you can link to classes and namespaces, you can’t drag classes or namespaces from the Class View onto the Layer Diagram design surface.&lt;/p&gt;  &lt;p&gt;The following diagram was created by dragging three projects from the Solution Explorer to the design surface and invoking Generate Dependencies on all three of the created layers:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/0511.LayerDiagram_5F00_3125EA18.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="Layer Diagram" border="0" alt="Layer Diagram" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/peterritchie.metablogapi/2570.LayerDiagram_5F00_thumb_5F00_0575201C.png" width="244" height="134" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Once a layer model has been defined, you can then ask Visual Studio to validate the solution against that logical architecture. Within the layer diagram you can have a one-to-one mapping of layer to links, or a one-to-many mapping.&amp;#160; i.e. a layer can consist of one or more links (at least in terms of validation—you can have zero links in a layer if you want; but then VS has no information with which to validate anything). If, for whatever reason, the current solution doesn’t follow the logical architecture, an error will result.&amp;#160;&amp;#160; You can also configure the solution to automatically validate the solution against the layer diagram during a build.&amp;#160; This build-time validate can occur in both the Ultimate and Premiums editions of Visual Studio 2010.&lt;/p&gt;  &lt;h2&gt;Why is it really just a Dependency Diagram?&lt;/h2&gt;  &lt;p&gt;Another really good question!&amp;#160; The Layer Diagram is really just a dependency diagram because there’s no inherent recognition for layer levels.&amp;#160; Because there’s no way of defining a level, there’s no way to group layers within a specific level.&amp;#160; Layer diagrams also allow bi-directional dependencies; a definite no-no with two layers at different levels.&amp;#160; It’s also really difficult to really enforce only a particular layer having references to particular external references.&amp;#160; You can declare forbidden namespaces for a particular layer, but it’s a cumbersome method of enforcing references to particular components only occur in a certain layer.&amp;#160; For example, if I had a DAL and I wanted to make sure only data-access occurred in that layer, I could add “System.Data” to the Forbidden Namespace Dependencies for all layers expect the DAL and incur an error with Layer Validation should any types from System.Data be used in any of those Layers.&amp;#160; But, things like DataGridView in Windows Forms are used primarily with types in System.Data so it becomes difficult to manage these dependencies.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1765201" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/peterritchie/archive/tags/DevCenterPost/default.aspx">DevCenterPost</category></item></channel></rss>