<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/1.5.1-alpha" -->
<rss version="2.0" 
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
>

<channel>
	<title>The blog of flying mind</title>
	<link>http://cahtter.blogsome.com</link>
	<description>Just another WordPress weblog</description>
	<pubDate>Tue, 25 Mar 2008 15:48:19 +0000</pubDate>
	<generator>http://wordpress.org/?v=1.5.1-alpha</generator>
	<language>en</language>

		<item>
		<title>Apartments and Pumping in the CLR</title>
		<link>http://cahtter.blogsome.com/2008/03/25/apartments-and-pumping-in-the-clr/</link>
		<comments>http://cahtter.blogsome.com/2008/03/25/apartments-and-pumping-in-the-clr/#comments</comments>
		<pubDate>Tue, 25 Mar 2008 15:48:19 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/25/apartments-and-pumping-in-the-clr/</guid>
		<description><![CDATA[	Also see: Brad Abrams&#8217; pixel8 Interview Podcast posted
	I&#8217;ve already written the much-delayed blog on Hosting, but I can&#8217;t post it yet because it mentions a couple of new Whidbey features, which weren&#8217;t present in the PDC bits.&nbsp; Obviously Microsoft doesn&#8217;t want to make product disclosures through my random blog articles.
	< ?xml:namespace prefix = o ns [...]]]></description>
			<content:encoded><![CDATA[	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I&#8217;ve already written the much-delayed blog on Hosting, but I can&#8217;t post it yet because it mentions a couple of new Whidbey features, which weren&#8217;t present in the PDC bits.<span style="mso-spacerun: yes">&nbsp; </span>Obviously Microsoft doesn&#8217;t want to make product disclosures through my random blog articles.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">< ?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I&#8217;m hoping this will be sorted out in another week or two.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>While we&#8217;re waiting, I thought I would talk briefly(!) about pumping and apartments.<span style="mso-spacerun: yes">&nbsp; </span>The CLR made some fundamental decisions about OLE, thread affinity, reentrancy and finalization.<span style="mso-spacerun: yes">&nbsp; </span>These decisions have a significant impact on program correctness, server scalability, and compatibility with legacy (i.e. unmanaged) code.<span style="mso-spacerun: yes">&nbsp; </span>So this is going to be a blog like the one on Shutdown from last August (see </font>http://blogs.msdn.com/cbrumme/archive/2003/08/20/51504.aspx <font face=Tahoma size=2>).<span style="mso-spacerun: yes">&nbsp; </span>There will be more detail than you probably care to know about one of the more frustrating parts of the Microsoft software stack.</font></p>
	<p><a id="more-31"></a><br />
<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/quaker-votes/"  title="Quaker votes">Quaker votes</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/the-internet-is-officially-dead-boring-its-the-economy-stupid/"  title="The Internet is Officially Dead &amp; Boring - Its the economy stupid !">The Internet is Officially Dead &amp; Boring - Its the economy stupid !</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/23/youtube-tries-to-get-legal-2/"  title="YouTube Tries to Get Legal">YouTube Tries to Get Legal</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/aspnet-mvc-in-codeplex-and-extensible-unit-testing/"  title="ASP.NET MVC in CodePlex and Extensible Unit Testing">ASP.NET MVC in CodePlex and Extensible Unit Testing</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/doing-the-deal-and-dishing-the-dirt/"  title="Doing the Deal and Dishing the Dirt">Doing the Deal and Dishing the Dirt</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/25/why-should-i-be-optimistic-about-trolltech-and-nokia-2/"  title="Why should I be optimistic about Trolltech and Nokia?">Why should I be optimistic about Trolltech and Nokia?</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>First, an explanation of my odd choice of terms.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;m using OLE as an umbrella which includes the following pieces of technology:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>COM &#8211; the fundamental object model, like IUnknown and IClassFactory</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>DCOM &#8211; remoting of COM using IDL, NDR pickling and the SCM</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span lang=FR style="mso-ansi-language: FR"><font size=2></font><font face=Tahoma>Automation &#8211; IDispatch, VARIANT, Type Libraries, etc.<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font size=2></font><font face=Tahoma>Active/X &#8211; Protocols for controls and their containers<span style="mso-spacerun: yes">&nbsp; </span></font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Next, some disclaimers:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I am not and have never been a GUI programmer.<span style="mso-spacerun: yes">&nbsp; </span>So anything I know about Windows messages and pumping is from debugging GUI applications, not from writing them.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;m not going to talk about WM_PENCTL notifications or anything else that requires UI knowledge.</font></p>
	<div class="interline">Multisoft Group: <a href="http://www.multisoftgroup.com/" title="Custom Software">Custom Software Development</a> and Consulting Service.
</div>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Also, I&#8217;m going to point out a number of problems with OLE and apartments.<span style="mso-spacerun: yes">&nbsp; </span>The history of the CLR and OLE are closely related.<span style="mso-spacerun: yes">&nbsp; </span>In fact, at one point COM+ 1.0 was known internally as COM98 and the CLR was known internally as COM99.<span style="mso-spacerun: yes">&nbsp; </span>We had some pretty aggressive ship targets back then!</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In general, I love OLE and the folks who work on it.<span style="mso-spacerun: yes">&nbsp; </span>Although it is inappropriate for the Internet, DCOM is still the fastest and most enterprise-ready distributed object system out there.<span style="mso-spacerun: yes">&nbsp; </span>In a few ways the architecture of.NET Remoting is superior to DCOM, but we never had the time or resources to even approach the engineering effort that has gone into DCOM.<span style="mso-spacerun: yes">&nbsp; </span>Presumably Indigo will eventually change this situation.<span style="mso-spacerun: yes">&nbsp; </span>I also love COM&#8217;s strict separation of contract from implementation, the ability to negotiate for contracts, and so much more.</font></p>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Help Desk Software">Help Desk Software</a>: Next generation of Live Chat. Jabber/XMPP Live Chat Server for a website.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/fix-returnurl-when-sharing-forms-authentication-with-multiple-web-applications/"  title="Fix ReturnUrl When Sharing Forms Authentication with Multiple Web Applications">Fix ReturnUrl When Sharing Forms Authentication with Multiple Web Applications</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/24/bloggers-in-the-mavs-locker-room-2/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/24/devweek-2008-cross-platform-silverlight-demos-2/"  title="DevWeek 2008 Cross Platform Silverlight Demos">DevWeek 2008 Cross Platform Silverlight Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/24/eriskay-a-programming-language-based-on-game-semantics-2/"  title="Eriskay: a Programming Language Based on Game Semantics">Eriskay: a Programming Language Based on Game Semantics</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/versioningdeploying-unmanaged-files/"  title="Versioning/Deploying Unmanaged Files">Versioning/Deploying Unmanaged Files</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/25/channel-9-interview-2/"  title="Channel 9 Interview">Channel 9 Interview</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/mix-08-sessions-published/"  title="Mix 08 Sessions Published">Mix 08 Sessions Published</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The bottom line is that OLE has had at least as much impact on Microsoft products and the industry, in its day, as.NET is having now.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But, like anything else, OLE has some flaws.<span style="mso-spacerun: yes">&nbsp; </span>In contrast to the stark architectural beauty of COM and DCOM, late-bound Automation is messy.<span style="mso-spacerun: yes">&nbsp; </span>At the time this was all rolled out to the world, I was at Borland and then Oracle.<span style="mso-spacerun: yes">&nbsp; </span>As an outsider, it was hard for me to understand how one team could have produced such a strange combination.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of course, Automation has been immensely successful &#8211; more successful than COM and DCOM.<span style="mso-spacerun: yes">&nbsp; </span>My aesthetic taste is clearly no predictor of what people want.<span style="mso-spacerun: yes">&nbsp; </span>Generally, people want whatever gets the job done, even if it does so in an ad hoc way.<span style="mso-spacerun: yes">&nbsp; </span>And Automation has enabled an incredible number of application scenarios.</font></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Softwre Development">Softwre Development</a> for small and middle size companies. World-class software applications.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/25/applied-metamodelling-a-foundation-for-language-driven-development-2/"  title="Applied Metamodelling: A Foundation for Language Driven Development">Applied Metamodelling: A Foundation for Language Driven Development</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/25/avoid-devpath-2/"  title="Avoid DevPath">Avoid DevPath</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/23/transparentproxy-2/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/24/devweek-2008-cross-platform-silverlight-demos-2/"  title="DevWeek 2008 Cross Platform Silverlight Demos">DevWeek 2008 Cross Platform Silverlight Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/23/ide-day-in-genoa-italy/"  title="IDE Day in Genoa, Italy">IDE Day in Genoa, Italy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/25/should-membership-stores-be-permitted-in-redmonds-manufacturing-park-zone-2/"  title="Should "Membership Stores" Be Permitted in Redmond's Manufacturing Park Zone?">Should &#8220;Membership Stores&#8221; Be Permitted in Redmond&#8217;s Manufacturing Park Zone?</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Apartments<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If there&#8217;s another part of OLE that I dislike, it&#8217;s Single Threaded Apartments.<span style="mso-spacerun: yes">&nbsp; </span>Presumably everyone knows that OLE offers three kinds of apartments:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font size=2></font><font face=Tahoma><u>Single Threaded Apartment (STA)</u> &#8211; one affinitized thread is used to call all the objects residing in the apartment.<span style="mso-spacerun: yes">&nbsp; </span>Any call on these objects from other threads must perform cross-thread marshaling to this affinitized thread, which dispatches the call.<span style="mso-spacerun: yes">&nbsp; </span>Although a process can have an arbitrary number of STAs (with a corresponding number of threads), most client processes have a single Main STA and the GUI thread is the affinitized thread that owns it.</font></p>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Help Server">Live Help Server</a>: Jerry Messenger is Jabber/XMPP Live Chat Server for a website.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/quaker-votes/"  title="Quaker votes">Quaker votes</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/24/bloggers-in-the-mavs-locker-room-2/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/25/a-vsnet-macro-to-generate-machine-keys/"  title="A VS.NET Macro to Generate Machine Keys.">A VS.NET Macro to Generate Machine Keys.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/25/ide-day-in-genoa-italy/"  title="IDE Day in Genoa, Italy">IDE Day in Genoa, Italy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfroms-second-bind/"  title="LoadFrom's Second Bind">LoadFrom&#8217;s Second Bind</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/25/a-quick-fix-for-the-validator-setfocusonerror-bug-2/"  title="A Quick Fix for the Validator SetFocusOnError Bug">A Quick Fix for the Validator SetFocusOnError Bug</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/bloggers-in-the-mavs-locker-room/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/25/loadassemblyname-2/"  title="Load(AssemblyName)">Load(AssemblyName)</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/23/ide-day-in-genoa-italy/"  title="IDE Day in Genoa, Italy">IDE Day in Genoa, Italy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/23/microformats-are-like-rfid-tags-for-the-web-2/"  title="Microformats are like RFID tags for the Web">Microformats are like RFID tags for the Web</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/bloggers-in-the-mavs-locker-room/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font size=2></font><font face=Tahoma><u>Multiple Threaded Apartment (MTA)</u> &#8211; each process has at most one MTA at a time.<span style="mso-spacerun: yes">&nbsp; </span>If the current MTA is not being used, OLE may tear it down.<span style="mso-spacerun: yes">&nbsp; </span>A different MTA will be created as necessary later.<span style="mso-spacerun: yes">&nbsp; </span>Most people think of the MTA as not having thread affinity.<span style="mso-spacerun: yes">&nbsp; </span>But strictly speaking it has affinity to a group of threads.<span style="mso-spacerun: yes">&nbsp; </span>This group is the set of all the threads that are not affinitized to STAs.<span style="mso-spacerun: yes">&nbsp; </span>Some of the threads in this group are explicitly placed in the MTA by calling CoInitializeEx.<span style="mso-spacerun: yes">&nbsp; </span>Other threads in this group are implicitly in the MTA because the MTA exists and because these threads haven&#8217;t been explicitly placed into STAs.<span style="mso-spacerun: yes">&nbsp; </span>So, by the strict rules of OLE, it is not legal for STA threads to call on any objects in the MTA.<span style="mso-spacerun: yes">&nbsp; </span>Instead, such calls must be marshaled from the calling STA thread over to one of the threads in the MTA before the call can legally proceed.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<div class="interline">Developing <a href="http://www.multisoftgroup.com/projects.html" title="Customer Relationship Management ">Customer Relationship Management</a> Solutions. Web, e-Commerce, Database Design and Software Development.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/java-design-operator-overloading-and-people/"  title="Java design, operator overloading and people">Java design, operator overloading and people</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/mix-08-sessions-published/"  title="Mix 08 Sessions Published">Mix 08 Sessions Published</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/25/the-exception-model/"  title="The Exception Model">The Exception Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/25/sourcegear-at-sd-west-next-week-2/"  title="SourceGear at SD West next week">SourceGear at SD West next week</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/24/dare-obasanjo-on-c-anonymous-types-2/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/25/from-c-to-java-part-3/"  title="From C# to Java:  Part 3">From C# to Java:  Part 3</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/25/channel-9-interview/"  title="Channel 9 Interview">Channel 9 Interview</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/25/ide-day-in-genoa-italy/"  title="IDE Day in Genoa, Italy">IDE Day in Genoa, Italy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/24/introducing-microsoft-tagspace-2/"  title="Introducing Microsoft Tagspace">Introducing Microsoft Tagspace</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/25/ide-day-in-genoa-italy/"  title="IDE Day in Genoa, Italy">IDE Day in Genoa, Italy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://thelivechatsoftware.blogsome.com/2008/03/24/2433-unread-emails-i-feel-your-pain/"  title="2,433 Unread Emails, I feel your pain..">2,433 Unread Emails, I feel your pain..</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/25/avoid-devpath-2/"  title="Avoid DevPath">Avoid DevPath</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/merry-christmas-indeed/"  title="Merry Christmas Indeed!">Merry Christmas Indeed!</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://spacechat.blogsome.com/2008/03/23/merry-christmas-indeed-2/"  title="Merry Christmas Indeed!">Merry Christmas Indeed!</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font size=2></font><font face=Tahoma><u>Neutral Apartment (NA)</u> &#8211; this is a recent invention (Win2000, I think).<span style="mso-spacerun: yes">&nbsp; </span>There is one NA in the process.<span style="mso-spacerun: yes">&nbsp; </span>Objects contained in the NA can be called from any thread in the process (STA or MTA threads).<span style="mso-spacerun: yes">&nbsp; </span>There are no threads associated with the NA, which is why it isn&#8217;t called NTA.<span style="mso-spacerun: yes">&nbsp; </span>Calls into NA objects can be relatively efficient because no thread marshaling is ever required.<span style="mso-spacerun: yes">&nbsp; </span>However, these cross-apartment calls still require a proxy to handle the transition between apartments.<span style="mso-spacerun: yes">&nbsp; </span>Calls from an object in the NA to an object in an STA or the MTA might require thread marshaling.<span style="mso-spacerun: yes">&nbsp; </span>This depends on whether or not the current thread is suitable for calling into the target object.<span style="mso-spacerun: yes">&nbsp; </span>For example, a call from an STA object to an NA object and from there to an MTA object will require thread marshaling during the transition out of the NA into the MTA.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Threading<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The MTA is effectively a free-threaded model.<span style="mso-spacerun: yes">&nbsp; </span>(It&#8217;s not quite a free-threaded model, because STA threads aren&#8217;t strictly allowed to call on MTA objects directly).<span style="mso-spacerun: yes">&nbsp; </span>From an efficiency point of view, it is the best threading model.<span style="mso-spacerun: yes">&nbsp; </span>Also, it imposes the least semantics on the application, which is also desirable.<span style="mso-spacerun: yes">&nbsp; </span>The main drawback with the MTA is that humans can&#8217;t reliably write free-threaded code.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Well, a few developers can write this kind of code if you pay them lots of money and you don&#8217;t ask them to write very much.<span style="mso-spacerun: yes">&nbsp; </span>And if you code review it very carefully.<span style="mso-spacerun: yes">&nbsp; </span>And you test it with thousands of machine hours, under very stressful conditions, on high-end MP machines like 8-ways and up.<span style="mso-spacerun: yes">&nbsp; </span>And you&#8217;re still prepared to chase down a few embarrassing race conditions once you&#8217;ve shipped your product.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But it&#8217;s not a good plan for the rest of us.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The NA model is truly free-threaded, in the sense that any thread in the process can call on these objects.<span style="mso-spacerun: yes">&nbsp; </span>All such threads must still transition through a proxy layer that maintains the apartment boundary.<span style="mso-spacerun: yes">&nbsp; </span>But within the NA all calls are direct and free-threaded.<span style="mso-spacerun: yes">&nbsp; </span>This is the only apartment that doesn&#8217;t involve thread affinity.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Although the NA is free-threaded, it is often used in conjunction with a lock to achieve rental threading.<span style="mso-spacerun: yes">&nbsp; </span>The rental model says that only one thread at a time can be active inside an object or a group of objects, but there is no restriction on which thread this might be.<span style="mso-spacerun: yes">&nbsp; </span>This is efficient because it avoids thread marshaling.<span style="mso-spacerun: yes">&nbsp; </span>Rather than marshaling a call from one thread to whatever thread is affinitized to the target objects, the calling thread simply acquires the lock (to rent the context) and then completes the call on the current thread.<span style="mso-spacerun: yes">&nbsp; </span>When the thread returns back out of the context, it releases the lock and now other threads can make calls.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you call out of a rental context into some other object (as opposed to the return pathway), you have a choice.<span style="mso-spacerun: yes">&nbsp; </span>You can keep holding the lock, in which case other threads cannot rent the context until you fully unwind.<span style="mso-spacerun: yes">&nbsp; </span>In this mode, the rental context supports recursion of the current thread, but it does not support reentrancy from other threads.<span style="mso-spacerun: yes">&nbsp; </span>Alternatively, the thread could release the lock when it calls out of the rental context, in which case it must reacquire the lock when it unwinds back and returns to the rental context.<span style="mso-spacerun: yes">&nbsp; </span>In this mode, the rental context supports full reentrancy.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Throughout this blog, we&#8217;ll be returning to this fundamental decision of whether to support reentrancy.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s a complex issue.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If only recursion is supported on a rental model, it&#8217;s clear that this is a much more forgiving world for developers than a free-threaded model.<span style="mso-spacerun: yes">&nbsp; </span>Once a thread has acquired the rental lock, no other threads can be active in the rented objects until the lock has been released.<span style="mso-spacerun: yes">&nbsp; </span>And the lock will not be released until the thread fully unwinds from the call into the context.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Even with reentrancy, the number of places where concurrency can occur is limited.<span style="mso-spacerun: yes">&nbsp; </span>Unless the renting thread calls out of the context, the lock won&#8217;t be released and the developer knows that other threads aren&#8217;t active within the rented objects.<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, it might be hard for the developer to know all the places that call out of the current context, releasing the lock.<span style="mso-spacerun: yes">&nbsp; </span>Particularly in a componentized world, or a world that combines application code with frameworks code, the developer can rarely have sufficient global knowledge.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So it sounds like limiting a rental context to same-thread recursion is better than allowing reentrancy during call outs, because the developer doesn&#8217;t have to worry about other threads mutating the state of objects in the rental context.<span style="mso-spacerun: yes">&nbsp; </span>This is true.<span style="mso-spacerun: yes">&nbsp; </span>But it also means that the resulting application is subject to more deadlocks.<span style="mso-spacerun: yes">&nbsp; </span>Imagine what can happen if two rental contexts are simultaneously making calls to each other.<span style="mso-spacerun: yes">&nbsp; </span>Thread T1 holds the lock to rent context C1.<span style="mso-spacerun: yes">&nbsp; </span>Thread T2 holds the lock to rent context C2.<span style="mso-spacerun: yes">&nbsp; </span>If T1 calls into C2 just as T2 calls into C1, and we are on the recursion plan, we have a classic deadlock.<span style="mso-spacerun: yes">&nbsp; </span>Two locks have been taken in different sequences by two different threads.<span style="mso-spacerun: yes">&nbsp; </span>Alternatively, if we are on a reentrancy plan, T1 will release the lock for C1 before contending for the lock on C2.<span style="mso-spacerun: yes">&nbsp; </span>And T2 will release the lock for C2 before contending for the lock on C1.<span style="mso-spacerun: yes">&nbsp; </span>The deadlock has been avoided, but T1 will find that the objects in C1 have been modified when it returns.<span style="mso-spacerun: yes">&nbsp; </span>And T2 will find similar surprises when it returns to C2.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Affinity<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway, we now understand the free-threaded model of the MTA and NA and we understand how to build a rental model on top of these via a lock.<span style="mso-spacerun: yes">&nbsp; </span>How about the single-threaded affinitized model of STAs?<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s hard to completely describe the semantics of an STA, because the complete description must incorporate the details of pages of OLE pumping code, the behavior of 3<sup>rd</sup> party IMessageFilters, etc.<span style="mso-spacerun: yes">&nbsp; </span>But generally an STA can be thought of as an <b style="mso-bidi-font-weight: normal">affinitized rental context</b> with <b style="mso-bidi-font-weight: normal">reentrancy</b> and <b style="mso-bidi-font-weight: normal">strict stacking</b>.<span style="mso-spacerun: yes">&nbsp; </span>By this I mean:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l4 level1 lfo1; tab-stops: list.5in"><font face=Tahoma size=2>It is <b style="mso-bidi-font-weight: normal">affinitized rental</b> because all calls into the STA must marshal to the correct thread and because only one logical call can be active in the objects of the apartment at any time.<span style="mso-spacerun: yes">&nbsp; </span>(This is necessarily the case, since there is only ever one thread).</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l4 level1 lfo1; tab-stops: list.5in"><font face=Tahoma size=2>It has <b style="mso-bidi-font-weight: normal">reentrancy</b> because every callout from the STA thread effectively releases the lock held by the logical caller and allows other logical callers to either enter or return back to the STA.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l4 level1 lfo1; tab-stops: list.5in"><font face=Tahoma size=2>It has <b style="mso-bidi-font-weight: normal">strict stacking</b> because one stack (the stack of the affinitized STA thread) is used to process all the logical calls that occur in the STA.<span style="mso-spacerun: yes">&nbsp; </span>When these logical calls perform a callout, the STA thread reentrantly picks up another call in, and this pushes the STA stack deeper.<span style="mso-spacerun: yes">&nbsp; </span>When the first callout wants to return to the STA, it must wait for the STA thread&#8217;s stack to pop all the way back to the point of its own callout.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>That point about strict stacking is a key difference between true rental and the affinitized rental model of an STA.<span style="mso-spacerun: yes">&nbsp; </span>With true rental, we never marshal calls between threads.<span style="mso-spacerun: yes">&nbsp; </span>Since each call occurs on its own thread, the pieces of stack for different logical threads are never mingled on an affinitized thread&#8217;s actual stack.<span style="mso-spacerun: yes">&nbsp; </span>Returns back into the rental context after a callout can be processed in any order.<span style="mso-spacerun: yes">&nbsp; </span>Returns back into an STA after a callout must be processed in a highly constrained order.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We&#8217;ve already seen a number of problems with STAs due to thread affinity, and we can add some more.<span style="mso-spacerun: yes">&nbsp; </span>Here&#8217;s the combined list:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l5 level1 lfo2; tab-stops: list.5in"><font face=Tahoma size=2>Marshaling calls between threads is expensive, compared to taking a lock.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=2>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l5 level1 lfo2; tab-stops: list.5in"><font face=Tahoma size=2>Processing returns from callouts in a constrained fashion can lead to inefficiencies.<span style="mso-spacerun: yes">&nbsp; </span>For instance, if the topmost return isn&#8217;t ready for processing yet, should the affinitized thread favor picking up a new incoming call (possibly leading to unconstrained stack growth) or should it favor waiting for the topmost return to complete (possibly idling the affinitized thread completely and conceivably resulting in deadlocks).</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=3>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l5 level1 lfo2; tab-stops: list.5in"><font face=Tahoma size=2>Any conventional locks held by an affinitized thread are worthless.<span style="mso-spacerun: yes">&nbsp; </span>The affinitized thread is processing an arbitrary number of logical calls, but a conventional lock (like an OS CRITICAL_SECTION or managed Monitor) will not distinguish between these logical calls.<span style="mso-spacerun: yes">&nbsp; </span>Instead, all lock acquisitions are performed by the single affinitized thread and are granted immediately as recursive acquisitions.<span style="mso-spacerun: yes">&nbsp; </span>If you are thinking of building a more sophisticated lock that avoids this issue, realize that you are making that classic reentrancy vs. deadlock decision all over again.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=4>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l5 level1 lfo2; tab-stops: list.5in"><font face=Tahoma size=2>Imagine a common server situation.<span style="mso-spacerun: yes">&nbsp; </span>The first call comes in from a particular client, creates a few objects (e.g. a shopping cart) and returns.<span style="mso-spacerun: yes">&nbsp; </span>Subsequent calls from that client manipulate that initial set of objects (e.g. putting some items into the shopping cart).<span style="mso-spacerun: yes">&nbsp; </span>A final call checks out the shopping cart, places the order, and all the objects are garbage collected.<span style="mso-spacerun: yes">&nbsp; </span>Now imagine that all those objects are affinitized to a particular thread.<span style="mso-spacerun: yes">&nbsp; </span>As a consequence, the dispatch logic of your server must ensure that all calls from the same client are routed to the same thread.<span style="mso-spacerun: yes">&nbsp; </span>And if that thread is busy doing other work, the dispatch logic must delay processing the new request until the appropriate affinitized thread is available.<span style="mso-spacerun: yes">&nbsp; </span>This is complicated and it has a severe impact on scalability.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=5>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l5 level1 lfo2; tab-stops: list.5in"><font face=Tahoma size=2>STAs must pump.<span style="mso-spacerun: yes">&nbsp; </span>(How did I get this far without mentioning pumping?)</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=6>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l5 level1 lfo2; tab-stops: list.5in"><font face=Tahoma size=2>Any STA code that assumed a single-threaded world for the process, rather than just for the apartment, might not pump.<span style="mso-spacerun: yes">&nbsp; </span>Such code breaks when we introduce the CLR into the process, as we will see.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Failure to Pump<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Let&#8217;s look at those last two bullet points in more detail.<span style="mso-spacerun: yes">&nbsp; </span>When your STA thread is doing nothing else, it needs to be checking to see if any other threads want to marshal some calls into it.<span style="mso-spacerun: yes">&nbsp; </span>This is done with a Windows message pump.<span style="mso-spacerun: yes">&nbsp; </span>If the STA thread fails to pump, these incoming calls will be blocked.<span style="mso-spacerun: yes">&nbsp; </span>If the incoming calls are GUI SendMessages or PostMessages (which I think of as synchronous or asynchronous calls respectively), then failure to pump will produce an unresponsive UI.<span style="mso-spacerun: yes">&nbsp; </span>If the incoming calls are COM calls, then failure to pump will result in calls timing out or deadlocking.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If processing one incoming call is going to take a while, it may be necessary to break up that processing with intermittent visits to the message pump.<span style="mso-spacerun: yes">&nbsp; </span>Of course, if you pump you are allowing reentrancy to occur at those points.<span style="mso-spacerun: yes">&nbsp; </span>So the developer loses all his wonderful guarantees of single threading.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Unfortunately, there&#8217;s a whole lot of STA code out there which doesn&#8217;t pump adequately.<span style="mso-spacerun: yes">&nbsp; </span>For the most part, we see this in non-GUI applications.<span style="mso-spacerun: yes">&nbsp; </span>If you have a GUI application that isn&#8217;t pumping enough, it&#8217;s obvious right there on the screen.<span style="mso-spacerun: yes">&nbsp; </span>Those bugs tend to get fixed.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>For non-GUI applications, a failure to pump may not be noticed in unmanaged code.<span style="mso-spacerun: yes">&nbsp; </span>When that code is moved to managed (perhaps by re-compiling some VB6 code as VB.NET), we start seeing bugs.<span style="mso-spacerun: yes">&nbsp; </span>Let&#8217;s look at a couple of real-world cases that we encountered during V1 of the CLR and how the lingering effects of these cases are still causing major headaches for managed developers and for Microsoft Support.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;ll describe a server case first, and then a client case.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font size=2></font><font face=Tahoma>< ?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><st1 :City w:st="on"></st1><st1 :place w:st="on"><b style="mso-bidi-font-weight: normal">ADO</b></st1><b style="mso-bidi-font-weight: normal"> and ASP Compatibility Mode<o :p></o></b></font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>ADO.NET and ASP.NET are a winning combination.<span style="mso-spacerun: yes">&nbsp; </span>But ASP.NET also supports an ASP compatibility mode.<span style="mso-spacerun: yes">&nbsp; </span>In this mode, legacy ASP pages can be served up by the managed ASP.NET pipeline.<span style="mso-spacerun: yes">&nbsp; </span>Such pages were written before we invented our managed platform, so they use <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> rather than ADO.NET for any data access.<span style="mso-spacerun: yes">&nbsp; </span>Also, in this mode the DCOM threadpool is used rather than the managed System.Threading.ThreadPool.<span style="mso-spacerun: yes">&nbsp; </span>Although all the threads in the managed ThreadPool are explicitly placed in the MTA (as you might hope and expect), the DCOM threadpool actually contains STA threads.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The purpose of this STA threadpool was to allow legacy STA COM objects in general, and VB6 objects in particular, to be moved from the client to the server.<span style="mso-spacerun: yes">&nbsp; </span>The result suffers from the scaling problems I alluded to before, since requests are dispatched on up to 100 STA threads with careful respect for any affinity.<span style="mso-spacerun: yes">&nbsp; </span>Also, VB6 has a variable scope which corresponds to &#8220;global&#8221; (I forget its name), but which is treated as per-thread when running on the server.<span style="mso-spacerun: yes">&nbsp; </span>If there are more than 100 clients using a server, multiple clients will share a single STA thread based on the whims of the request dispatch logic.<span style="mso-spacerun: yes">&nbsp; </span>This means that global variables are shared between sets of clients in a surprising fashion, based on the STA that they happen to correspond to.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>A typical ASP page written in VBScript would establish a (hopefully pooled) database connection from <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1>, query up a row, modify a field, and write the row back to the database.<span style="mso-spacerun: yes">&nbsp; </span>Since the page was likely written in VB, any COM AddRef and Release calls on the <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> row and field value objects were supplied through the magic of the VB6 runtime.<span style="mso-spacerun: yes">&nbsp; </span>This means they occur on the same thread and in a very deterministic fashion.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The ASP page contains no explicit pumping code.<span style="mso-spacerun: yes">&nbsp; </span>Indeed, at no point was the STA actually pumped.<span style="mso-spacerun: yes">&nbsp; </span>Although this is a strict violation of the rules, it didn&#8217;t cause any problems.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because there are no GUI messages or inter-apartment COM calls that need to be serviced.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This technique of executing ASP pages on STAs with <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> worked fairly well &#8211; until we tried to extend the model to ASP.NET running in ASP compatibility mode.<span style="mso-spacerun: yes">&nbsp; </span>The first problem that we ran into was that all managed applications are automatically multi-threaded.<span style="mso-spacerun: yes">&nbsp; </span>For any application of reasonable complexity, there are sure to be at least a few finalizable objects.<span style="mso-spacerun: yes">&nbsp; </span>These objects will have their Finalize methods called by one or more dedicated finalizer threads that are distinct from the application threads.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>(It&#8217;s important that finalization occurs on non-application threads, since we don&#8217;t want to be holding any application locks when we call the Finalize method.<span style="mso-spacerun: yes">&nbsp; </span>And today the CLR only has a single Finalizer thread, but this is an implementation detail.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s quite likely that in the future we will concurrently call Finalize methods on many objects, perhaps by moving finalization duties over to the ThreadPool.<span style="mso-spacerun: yes">&nbsp; </span>This would address some scalability concerns with finalization, and would also allow us to make stronger guarantees about the availability of the finalization service).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Our COM Interop layer ensures that we almost only ever call COM objects in the correct apartment and context.<span style="mso-spacerun: yes">&nbsp; </span>The one place where we violate COM rules is when the COM object&#8217;s apartment or context has been torn down.<span style="mso-spacerun: yes">&nbsp; </span>In that case, we will still call IUnknown::Release on the pUnk to try to recover its resources, even though this is strictly illegal.<span style="mso-spacerun: yes">&nbsp; </span>We&#8217;ve gone backwards and forwards on whether this is appropriate, and we provide a Customer Debug Probe so that you can detect whether this is happening in your application.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway, let&#8217;s pretend that we absolutely always call the pUnk in the correct apartment and context.<span style="mso-spacerun: yes">&nbsp; </span>In the case of an object living in an STA, this means that the Finalizer thread will marshal the call to the affinitized thread of that STA.<span style="mso-spacerun: yes">&nbsp; </span>But if that STA thread is not pumping, the Finalizer thread will block indefinitely while attempting to perform the cross-thread marshaling.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The effect on a server is crippling.<span style="mso-spacerun: yes">&nbsp; </span>The Finalizer thread makes no progress.<span style="mso-spacerun: yes">&nbsp; </span>The number of unreleased pUnks grows without bounds.<span style="mso-spacerun: yes">&nbsp; </span>Eventually some resource (usually memory) is exceeded and the process crashes.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>One solution is to edit the original ASP page to pump the underlying STA thread that it is executing on.<span style="mso-spacerun: yes">&nbsp; </span>A light-weight way to pump is to call Thread.CurrentThread.Join(0).<span style="mso-spacerun: yes">&nbsp; </span>This causes the current thread to block until the current thread dies (which isn&#8217;t going to happen) or until 0 milliseconds have elapsed &#8211; whichever happens first.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;ll explain later why this also performs <i style="mso-bidi-font-style: normal">some</i> pumping and why this is a controversial aspect of the CLR.<span style="mso-spacerun: yes">&nbsp; </span>A heavier-weight way to pump is to call GC.WaitForPendingFinalizers.<span style="mso-spacerun: yes">&nbsp; </span>This not only performs pumping, but it also waits for the Finalization queue to drain.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you are porting a page that produces a modest number of COM objects, doing a simple Join on each page may be sufficient.<span style="mso-spacerun: yes">&nbsp; </span>If your page performs elaborate processing, perhaps creating an unbounded number of COM objects in a loop, then you may need to either add a Join within the loop or WaitForPendingFinalizers at the end of the page processing.<span style="mso-spacerun: yes">&nbsp; </span>The only way to really know is to experiment with both techniques, measuring the growth of the Finalization queue and the impact on server throughput.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>ADO&#8217;s Threading Model<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There was another problem with using <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> from ASP.NET&#8217;s ASP compatibility mode.<span style="mso-spacerun: yes">&nbsp; </span>Do you know what the threading model of <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> is?<span style="mso-spacerun: yes">&nbsp; </span>Well, if you check the registry for some ADO CLSIDs on your machine, you may find them registered as ThreadingModel=Single or you may find them registered as ThreadingModel=Both.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If these classes are registered as Single, OLE will carefully ensure that their instances can only be called from the thread that they were created on.<span style="mso-spacerun: yes">&nbsp; </span>This implies that the objects can assume a single-threaded view of the world and they do not need to be written in a thread-safe manner.<span style="mso-spacerun: yes">&nbsp; </span>If these classes are registered as Both, OLE will ensure that their instances are only called from threads in the right apartment.<span style="mso-spacerun: yes">&nbsp; </span>But if that apartment is the MTA, these objects better have been written in a thread-safe manner.<span style="mso-spacerun: yes">&nbsp; </span>For example, they had better be using InterlockedIncrement and Decrement, or an equivalent, for reference counting.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Unfortunately, the <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> classes are not thread-safe.<span style="mso-spacerun: yes">&nbsp; </span>Strictly speaking, they should never be registered as anything but Single.<span style="mso-spacerun: yes">&nbsp; </span>You may find them registered as Both on your machine because this improves scalability and throughput for some key scenarios.<span style="mso-spacerun: yes">&nbsp; </span>And those key scenarios happen to limit themselves to &#8220;one thread at a time&#8221; because of how ASP and VB6 work.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In fact, the legacy <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> classes don&#8217;t even support single-threaded access if there is reentrancy.<span style="mso-spacerun: yes">&nbsp; </span>They will randomly crash when used in this manner (and this is exactly the manner in which <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> was driven in the early days of V1).<span style="mso-spacerun: yes">&nbsp; </span>Here are the steps:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>The page queries up an <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> row object, which enters managed code via COM Interop as an RCW (runtime-callable wrapper).</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>By making a COM call on this RCW, the page navigates to a field value.<span style="mso-spacerun: yes">&nbsp; </span>This field value also enters managed code via COM Interop as an RCW.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>The page now makes a COM call via <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> which results in a call out to the remote database.<span style="mso-spacerun: yes">&nbsp; </span>At this point, the STA thread is pumped by the DCOM remote call.<span style="mso-spacerun: yes">&nbsp; </span>Since this is a remote call, it&#8217;s going to take a while before it returns.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>The garbage collector decides that it&#8217;s time to collect.<span style="mso-spacerun: yes">&nbsp; </span>At this point, the RCW for the field value is still reachable and is reported.<span style="mso-spacerun: yes">&nbsp; </span>The RCW for the row object is no longer referenced by managed code and is collected.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>The Finalizer thread notices that the pUnk underlying the row&#8217;s RCW is no longer in use, and it makes the cross-apartment call from the Finalizer thread&#8217;s apartment (MTA) to the <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> row object&#8217;s apartment (STA).</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>Recall that the STA thread is pumping for the duration of the remote database call (#3 above).<span style="mso-spacerun: yes">&nbsp; </span>It picks up the cross-thread call from the Finalizer (#5 above) and performs the Release on the Row object.<span style="mso-spacerun: yes">&nbsp; </span>This is the final Release and <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> deletes the unmanaged Row object from memory.<span style="mso-spacerun: yes">&nbsp; </span>This logical call unwinds and the Finalizer thread is unblocked (hurray).<span style="mso-spacerun: yes">&nbsp; </span>The STA thread returns to pumping.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>The remote database call returns back to the server machine.<span style="mso-spacerun: yes">&nbsp; </span>The STA thread picks it up from its pumping loop and returns back to the page, unwinding the thread.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font face=Tahoma size=2>The page now updates the field value, which involves a COM call to the underlying <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> object.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo3; tab-stops: list.5in"><font size=2></font><font face=Tahoma><st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> crashes or randomly corrupts memory.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>What happened?<span style="mso-spacerun: yes">&nbsp; </span>The <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> developers made a questionable design decision when they implemented COM reference counting throughout their hierarchy.<span style="mso-spacerun: yes">&nbsp; </span>The field values refer to their owning row object, but they don&#8217;t hold a reference count on that row.<span style="mso-spacerun: yes">&nbsp; </span>Instead, they assume that the row will live as long as all of its associated field values.<span style="mso-spacerun: yes">&nbsp; </span>And yet, whenever the application makes an <st1 :place w:st="on"></st1><st1 :City w:st="on">ADO</st1> call on a field value, the field value will access that (hopefully present) row.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This assumption worked fine in the days of ASP and VB6.<span style="mso-spacerun: yes">&nbsp; </span>So nobody even noticed the bug until the CLR violated those threading assumptions &#8211; without violating the underlying OLE rules, of course.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>It was impractical to fix this by opening up <st1 :place w:st="on"></st1><st1 :City w:st="on">ADO</st1> and rewriting the code.<span style="mso-spacerun: yes">&nbsp; </span>There are many different versions of <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> in existence, and many products that distribute it.<span style="mso-spacerun: yes">&nbsp; </span>Another option was to add GC.KeepAlive(row) calls at the bottom of each page, to extend the lifetime of the row objects until the field values were no longer needed.<span style="mso-spacerun: yes">&nbsp; </span>This would have been a nightmare for Support.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Instead, the <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> team solved the problem for managed code with a very elegant technique.<span style="mso-spacerun: yes">&nbsp; </span>(I invented it, so of course I think it was elegant).<span style="mso-spacerun: yes">&nbsp; </span>They opened up the assembly that was created by TlbImp&#8217;ing ADO.<span style="mso-spacerun: yes">&nbsp; </span>Then they added managed references from the RCWs of the field values to the RCWs of their owning rows.<span style="mso-spacerun: yes">&nbsp; </span>These managed references are completely visible to the garbage collector.<span style="mso-spacerun: yes">&nbsp; </span>Now the GC knows that if the field values are reachable then the row values must also be reachable.<span style="mso-spacerun: yes">&nbsp; </span>Problem solved.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b><font size=2></font><font face=Tahoma>No Typelib Registered<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Incidentally, we ran into another very common problem when we moved existing client or server COM applications over to managed code.<span style="mso-spacerun: yes">&nbsp; </span>Whenever an application uses a COM object, it tries hard to match the thread of the client to the ThreadingModel of the server.<span style="mso-spacerun: yes">&nbsp; </span>In other words, if the application needs to use a ThreadingModel=Main COM object, the application tries to ensure that the creating thread is in an STA.<span style="mso-spacerun: yes">&nbsp; </span>Similarly, if the application needs to use a ThreadingModel=Free COM object, it tries to create this object from an MTA thread.<span style="mso-spacerun: yes">&nbsp; </span>Even if a COM object is ThreadingModel=Both, the application will try to access the object from the same sort of thread (STA vs. MTA) as the thread that created the object.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>One reason for doing this is performance.<span style="mso-spacerun: yes">&nbsp; </span>If you can avoid an apartment transition, your calls will be much faster.<span style="mso-spacerun: yes">&nbsp; </span>Another reason has to do with pumping and reentrancy.<span style="mso-spacerun: yes">&nbsp; </span>If you make a cross-apartment call into an STA, the STA better be pumping to pick up your call.<span style="mso-spacerun: yes">&nbsp; </span>And if you make a cross-apartment call out of an STA, your thread will start pumping and your application becomes reentrant.<span style="mso-spacerun: yes">&nbsp; </span>This is a small dose of free-threading, and many application assumptions start to break.<span style="mso-spacerun: yes">&nbsp; </span>A final reason for avoiding apartment transitions is that they often aren&#8217;t supported.<span style="mso-spacerun: yes">&nbsp; </span>For instance, most ActiveX scenarios require that the container and the control are in the same STA.<span style="mso-spacerun: yes">&nbsp; </span>If you introduce an apartment boundary (even between two STAs), bizarre cases like Input Synchronous messages stop working properly.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The net result is that a great many applications avoid using COM objects across apartment boundaries.<span style="mso-spacerun: yes">&nbsp; </span>And this means that &#8211; even if that COM object is nominally marshalable across an apartment boundary &#8211; this often isn&#8217;t being tested.<span style="mso-spacerun: yes">&nbsp; </span>So an application might install itself without ensuring that the typelib of the COM component is actually registered.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>When the application is moved to managed code, developers are frustrated to see InvalidCastExceptions on the managed side.<span style="mso-spacerun: yes">&nbsp; </span>A typical sequence is that they successfully &#8216;new&#8217; the COM object, implying that the CoCreate returned a pUnk which was wrapped in an RCW.<span style="mso-spacerun: yes">&nbsp; </span>Then when they cast it to one of the interfaces that they know is supported, a casting exception is thrown.<span style="mso-spacerun: yes">&nbsp; </span>This casting exception is due to a QueryInterface call failing with E_NOINTERFACE.<span style="mso-spacerun: yes">&nbsp; </span>Yet this HRESULT is not returned by the COM object, which does indeed support the interface.<span style="mso-spacerun: yes">&nbsp; </span>Instead, it is returned by a COM apartment proxy which sits between the RCW and that COM object.<span style="mso-spacerun: yes">&nbsp; </span>The COM apartment proxy is simply failing to marshal the interface across the apartment boundary &#8211; usually because the COM object is using the OLEAUT marshaler and the Typelib has not been properly registered.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is a common failure, and it&#8217;s unfortunate that a generic E_NOINTERFACE doesn&#8217;t lead to better debuggability for this case.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Finally, I can&#8217;t help but mention that the COM Interop layer added other perturbations to many unmanaged COM scenarios that seemed to be working just fine.<span style="mso-spacerun: yes">&nbsp; </span>Common perturbations from managed code include garbage collection, a Finalizer thread, strict conformance to OLE marshaling rules, and the fact that managed objects are agile with respect to COM apartments and COM+ contexts (unless they derive from ServicedComponent).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>For instance, Trident required that all calls on its objects occur on the correct thread.<span style="mso-spacerun: yes">&nbsp; </span>But Trident also had an extension model where 3<sup>rd</sup> party objects could be aggregated onto their base objects.<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, the aggregator performed blind delegation to the 3<sup>rd</sup> party objects.<span style="mso-spacerun: yes">&nbsp; </span>And &#8211; even more unfortunate &#8211; this blind delegation did not exclude QI&#8217;s for IMarshal.<span style="mso-spacerun: yes">&nbsp; </span>Of course, managed objects implement IMarshal to achieve their apartment and context agility.<span style="mso-spacerun: yes">&nbsp; </span>So if Trident aggregated a managed object as an extention, the containing Trident object would attempt to become partially agile in a very broken way.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Hopefully we found and dealt with most of these issues before we shipped V1.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="mso-spacerun: yes"><font face=Tahoma size=2></font></span>&nbsp;</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Not Pumping a Client<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I said I would describe two cases where non-pumping unmanaged code caused problems when we moved to managed code.<span style="mso-spacerun: yes">&nbsp; </span>The above explains, in great detail, how <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> and ASP compatibility mode caused us problems on the server.<span style="mso-spacerun: yes">&nbsp; </span>Now let&#8217;s look at the non-GUI client case.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We all know that a WinForms GUI client is going to put the main GUI thread into an STA.<span style="mso-spacerun: yes">&nbsp; </span>And we know that there&#8217;s a lot of pumping in a GUI application, or else not much is going to show on the screen.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Assume for a moment that a Console application also puts its main thread into an STA.<span style="mso-spacerun: yes">&nbsp; </span>If that main thread creates any COM objects via COM Interop, and if those COM objects are ThreadingModel=<st1 :place w:st="on">Main</st1> or Both, then the application better be pumping.<span style="mso-spacerun: yes">&nbsp; </span>If it fails to pump, we&#8217;ll have exactly the same situation with our server running ASP compatibility mode.<span style="mso-spacerun: yes">&nbsp; </span>The Finalizer thread won&#8217;t be able to marshal calls into the STA to Release any pUnks.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>On a well-loaded server, that failure is quickly noticed by the developer or by the folks in operations.<span style="mso-spacerun: yes">&nbsp; </span>But on a client, this might be just a mild case of constipation.<span style="mso-spacerun: yes">&nbsp; </span>The rate of creation of finalizable objects may be low enough that the problem is never noticed.<span style="mso-spacerun: yes">&nbsp; </span>Or it may be noticed as a gradual build up of resources.<span style="mso-spacerun: yes">&nbsp; </span>If the problem is reported to Microsoft Support, the customer generally categorizes it as a garbage collection bug.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So what is the apartment of a Console application&#8217;s main thread?<span style="mso-spacerun: yes">&nbsp; </span>Well, it depends.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you build a Console application in Notepad, the main thread is likely to start off in the MTA.<span style="mso-spacerun: yes">&nbsp; </span>If you build a Console application with Visual Studio, then if you pick C# or VB.NET your main thread is likely to be in an STA.<span style="mso-spacerun: yes">&nbsp; </span>If you build a Console application with Visual Studio and you choose managed C++, your main thread is likely to be in an MTA for V1 or V1.1.<span style="mso-spacerun: yes">&nbsp; </span>I think it&#8217;s likely to be in an STA for our next release.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Wow.<span style="mso-spacerun: yes">&nbsp; </span>Why are we all over the place on this?<span style="mso-spacerun: yes">&nbsp; </span>Mostly, it&#8217;s because there is no correct answer.<span style="mso-spacerun: yes">&nbsp; </span>Either the developer is not going to use any COM objects in his Console application, in which case the choice doesn&#8217;t really matter, or the developer is going to use some COM objects and this should inform his decision.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>For instance, if the developer will use COM objects with ThreadingModel=<st1 :place w:st="on">Main</st1>, he probably wants to put his main thread into an STA so he can use the COM objects directly without cross-thread marshaling and all the issues that this would imply.<span style="mso-spacerun: yes">&nbsp; </span>This means he should also pump that thread, if there are other threads (like the Finalizer!) active in the process.<span style="mso-spacerun: yes">&nbsp; </span>Alternatively, if the developer intends to use COM objects with ThreadingModel=Free, he probably wants to put his main thread in the MTA so he can access those objects directly.<span style="mso-spacerun: yes">&nbsp; </span>Now he doesn&#8217;t need to pump, but he does need to consider the implications of writing free-threaded code.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Either way, the developer has some responsibility.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Unfortunately, the choice of a default is typically made by the project type that he selects in Visual Studio, or is based on the CLR&#8217;s default behavior (which favors MTA).<span style="mso-spacerun: yes">&nbsp; </span>And realistically the subtleties of apartments and pumping are beyond the knowledge (or interest) of most managed developers.<span style="mso-spacerun: yes">&nbsp; </span>Let&#8217;s face it: nobody should have to worry about this sort of thing.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>The Managed CoInitialize Mess<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There are three ways to select an apartment choice for the main thread of your Console application.<span style="mso-spacerun: yes">&nbsp; </span>All three of these techniques have concerns associated with them.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l2 level1 lfo4; tab-stops: list.5in"><span style="mso-bidi-font-family: Tahoma; mso-fareast-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>You can place either an STAThreadAttribute or MTAThreadAttribute onto the main method.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l2 level1 lfo4; tab-stops: list.5in"><span style="mso-bidi-font-family: Tahoma; mso-fareast-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>You can perform an assignment to System.Threading.CurrentThread.ApartmentState as one of the first statements of your main method (or of your thread procedure if you do a Thread.Start).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l2 level1 lfo4; tab-stops: list.5in"><span style="mso-bidi-font-family: Tahoma; mso-fareast-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>3)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>You can accept the CLR&#8217;s default of MTA.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So what&#8217;s wrong with each of these techniques?</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The first technique is the preferred method, and it works very well for C#.<span style="mso-spacerun: yes">&nbsp; </span>After some tweaks to the VB.NET compiler before we shipped V1, it worked well for VB too.<span style="mso-spacerun: yes">&nbsp; </span>Managed C++ still doesn&#8217;t properly support this technique.<span style="mso-spacerun: yes">&nbsp; </span>The reason is that the entrypoint of a managed C++ EXE isn&#8217;t actually your &#8216;main&#8217; routine.<span style="mso-spacerun: yes">&nbsp; </span>Instead, it&#8217;s a method inside the C-runtime library.<span style="mso-spacerun: yes">&nbsp; </span>That method eventually delegates to your &#8216;main&#8217; routine.<span style="mso-spacerun: yes">&nbsp; </span>But the CLR doesn&#8217;t scan through the closure of calls from the entrypoint when looking for the custom attribute that defines the threading model.<span style="mso-spacerun: yes">&nbsp; </span>If the CLR doesn&#8217;t find it on the method that is the EXE&#8217;s entrypoint, it stops looking.<span style="mso-spacerun: yes">&nbsp; </span>The net result is that your attribute is quietly ignored for C++.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I&#8217;m told that this will be addressed in Whidbey, by having the linker propagate the attribute from &#8216;main&#8217; to the CRT entrypoint.<span style="mso-spacerun: yes">&nbsp; </span>And indeed this is how the VB.NET compiler works today.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>What&#8217;s wrong with the second technique?<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, it is subject to a race condition.<span style="mso-spacerun: yes">&nbsp; </span>Before the CLR can actually call your thread procedure, it may first call some module constructors, class constructors, AssemblyLoad notifications and AssemblyResolve notifications.<span style="mso-spacerun: yes">&nbsp; </span>All of this execution occurs on the thread that was just created.<span style="mso-spacerun: yes">&nbsp; </span>What happens if some of these methods set the thread&#8217;s ApartmentState before you get a chance?<span style="mso-spacerun: yes">&nbsp; </span>What happens if they call Windows services like the clipboard that also set the apartment state?<span style="mso-spacerun: yes">&nbsp; </span>A more likely scenario is that one of these other methods will make a PInvoke call that marshals a BSTR, SAFEARRAY or VARIANT.<span style="mso-spacerun: yes">&nbsp; </span>Even these innocuous operations can force a CoInitializeEx on your thread and limit your ability to configure the thread from your thread procedure.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>When you are developing your application, none of the above is likely to occur.<span style="mso-spacerun: yes">&nbsp; </span>The real nightmare scenario is that a future version of the CLR will provide a JIT that inlines a little more aggressively, so some extra class constructors execute before your thread procedure.<span style="mso-spacerun: yes">&nbsp; </span>In other words, you will ship an application that is balanced on a knife edge here, and this will become an App Compatibility issue for all of us.<span style="mso-spacerun: yes">&nbsp; </span>(See </font>http://blogs.msdn.com/cbrumme/archive/2003/11/10/51554.aspx <font face=Tahoma size=2> for more details on the sort of thing we worry about here).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In fact, for the next release of the CLR we are seriously considering making it impossible to set the apartment state on a running thread in this manner.<span style="mso-spacerun: yes">&nbsp; </span>At a minimum, you should expect to see a Customer Debug Probe warning of the risk here.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>And the third technique from above has a similar problem.<span style="mso-spacerun: yes">&nbsp; </span>Recall that threads in the MTA can be explicitly placed there through a CoInitializeEx call, or they can be implicitly treated as being in the MTA because they haven&#8217;t been placed into an STA.<span style="mso-spacerun: yes">&nbsp; </span>The difference between these two cases is significant.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If a thread is explicitly in the MTA, any attempt to configure it as an STA thread will fail with an error of RPC_E_CHANGED_MODE.<span style="mso-spacerun: yes">&nbsp; </span>By contrast, if a thread is implicitly in the MTA it can be moved to an STA by calling CoInitializeEx.<span style="mso-spacerun: yes">&nbsp; </span>This is more likely than it may sound.<span style="mso-spacerun: yes">&nbsp; </span>If you attempt a clipboard operation, or you call any number of other Windows services, the code you call may attempt to place your thread in the STA.<span style="mso-spacerun: yes">&nbsp; </span>And when you accept the CLR default behavior, it currently leaves the thread implicitly in the MTA and therefore is subject to reassignment.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is another place where we are seriously considering changing the rules in the next version of the CLR.<span style="mso-spacerun: yes">&nbsp; </span>Rather than place threads implicitly in the MTA, we are considering making this assignment explicit and preventing any subsequent reassignment.<span style="mso-spacerun: yes">&nbsp; </span>Once again, our motivation is to reduce the App Compat risk for applications after they have been deployed.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Speaking of race conditions and apartments, the CLR has a nasty bug which was introduced in V1 and which we have yet to remove.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;ve already mentioned that any threads that aren&#8217;t in STAs or explicitly in the MTA are implicitly in the MTA.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s not strictly true.<span style="mso-spacerun: yes">&nbsp; </span>These threads are only in the MTA if there is an MTA for them to be in.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There is an MTA if OLE is active in the process and if at least one thread is explicitly in the MTA.<span style="mso-spacerun: yes">&nbsp; </span>When this is the case, all the other unconfigured threads are implicitly in the MTA.<span style="mso-spacerun: yes">&nbsp; </span>But if that one explicit thread should terminate or CoUninitialize, then OLE will tear down the MTA.<span style="mso-spacerun: yes">&nbsp; </span>A different MTA may be created later, when a thread explicitly places itself into it.<span style="mso-spacerun: yes">&nbsp; </span>And at that point, all the unconfigured threads will implicitly join it.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But this destruction and recreation of the MTA has some serious impacts on COM Interop.<span style="mso-spacerun: yes">&nbsp; </span>In fact, any changes to the apartment state of a thread can confuse our COM Interop layer, cause deadlocks on downlevel platforms, and lead to memory leaks and violation of OLE rules.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Let&#8217;s look at how this specific race condition occurs first, and then I&#8217;ll talk about the larger problems here.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l1 level1 lfo5; tab-stops: list.5in"><font face=Tahoma size=2>An unmanaged thread CoInitializes itself for the MTA and calls into managed code.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l1 level1 lfo5; tab-stops: list.5in"><font face=Tahoma size=2>While in managed code, that thread introduces some COM objects to our COM Interop layer in the form of RCWs, perhaps by &#8216;new&#8217;ing them from managed code.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l1 level1 lfo5; tab-stops: list.5in"><font face=Tahoma size=2>The CLR notices that the current thread is in the MTA, and realizes that it must &#8220;keep the MTA alive.&#8221;<span style="mso-spacerun: yes">&nbsp; </span>We signal the Finalizer thread to put itself explicitly into the MTA via CoInitializeEx.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l1 level1 lfo5; tab-stops: list.5in"><font face=Tahoma size=2>The unmanaged thread returns out to unmanaged code where it either dies or simply calls CoUninitialize.<span style="mso-spacerun: yes">&nbsp; </span>The MTA is torn down.</font></li>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l1 level1 lfo5; tab-stops: list.5in"><font face=Tahoma size=2>The Finalizer thread wakes up and explicitly CoInitializes itself into the MTA.<span style="mso-spacerun: yes">&nbsp; </span>Oops.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s too late to keep the original MTA alive and it has the effect of creating a new MTA.<span style="mso-spacerun: yes">&nbsp; </span>At least <i>this</i> one will live until the end of the process.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>As far as I know, this is the only race condition in the CLR that we haven&#8217;t fixed.<span style="mso-spacerun: yes">&nbsp; </span>Why have we ignored it all these years?<span style="mso-spacerun: yes">&nbsp; </span>First, we&#8217;ve never seen it reported from the field.<span style="mso-spacerun: yes">&nbsp; </span>This isn&#8217;t so surprising when you consider that the application often shares responsibility for keeping the MTA alive.<span style="mso-spacerun: yes">&nbsp; </span>Many applications are aware of this obligation and &#8211; if they use COM &#8211; they always keep an outstanding CoInitialize on one MTA thread so the apartment won&#8217;t be torn down.<span style="mso-spacerun: yes">&nbsp; </span>Second, I generally resist fixing bugs by adding inter-thread dependencies.<span style="mso-spacerun: yes">&nbsp; </span>It would be all too easy to create a deadlock by making step 3 wait for the Finalizer thread to CoInitialize itself, rather than just signaling it to do so.<span style="mso-spacerun: yes">&nbsp; </span>This is particularly true since the causality of calls from the Finalizer to other threads is often opaque to us, as I&#8217;ll explain later.<span style="mso-spacerun: yes">&nbsp; </span>And we certainly don&#8217;t want to create a dedicated thread for this purpose.<span style="mso-spacerun: yes">&nbsp; </span>Dedicated threads have a real impact on Terminal Server scenarios, where the cost of one thread in a process is multiplied by all the processes that are running.<span style="mso-spacerun: yes">&nbsp; </span>Even if we were prepared to pay this cost, we would want to create this thread lazily.<span style="mso-spacerun: yes">&nbsp; </span>But synchronizing with the creation of another thread is always a dangerous proposition.<span style="mso-spacerun: yes">&nbsp; </span>Thread creation involves taking the OS loader lock and making DLL_THREAD_ATTACH notifications to all the DllMain routines that didn&#8217;t explicitly disable these calls.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The bottom line is that the fix is expensive and distasteful.<span style="mso-spacerun: yes">&nbsp; </span>And it speaks to a more general problem, where many different components in a process may be individually spinning up threads to keep the MTA from being recycled.<span style="mso-spacerun: yes">&nbsp; </span>A better solution is for OLE to provide an API to keep this apartment alive, without requiring all those dedicated threads.<span style="mso-spacerun: yes">&nbsp; </span>This is the approach that we are pursuing for the long term.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In our general cleanup of the CLR&#8217;s treatment of CoInitialize, we are also likely to change the semantics of assigning the current thread&#8217;s ApartmentState to Unknown.<span style="mso-spacerun: yes">&nbsp; </span>In V1 &amp; V1.1 of the CLR, any attempt to set the state to Unknown would throw an ArgumentOutOfRangeException, so we&#8217;re confident that we can make this change without breaking applications.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If the CLR has performed an outstanding CoInitializeEx on this thread, we may treat the assignment to Unknown as a request to perform a CoUninitialize to reverse the operation.<span style="mso-spacerun: yes">&nbsp; </span>Currently, the only way you can CoUninitialize a thread is to PInvoke to the OLE32 service.<span style="mso-spacerun: yes">&nbsp; </span>And such changes to the apartment state are uncoordinated with the CLR.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Now why does it matter if the apartment state of a thread changes, without the CLR knowing?<span style="mso-spacerun: yes">&nbsp; </span>It matters because:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l0 level1 lfo6; tab-stops: list.5in"><span style="mso-bidi-font-family: Tahoma; mso-fareast-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>The CLR may hold RCWs over COM objects in the apartment that is about to disappear.<span style="mso-spacerun: yes">&nbsp; </span>Without a notification, we cannot legally release those pUnks. <span style="mso-spacerun: yes">&nbsp;</span>As I&#8217;ve already mentioned, we break the rules here and attempt to Release anyway.<span style="mso-spacerun: yes">&nbsp; </span>But it&#8217;s still a very bad situation and sometimes we will end up leaking.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l0 level1 lfo6; tab-stops: list.5in"><span style="mso-bidi-font-family: Tahoma; mso-fareast-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>The CLR will perform limited pumping of STA threads when you perform managed blocking (e.g. WaitHandle.WaitOne).<span style="mso-spacerun: yes">&nbsp; </span>If we are on a recent OS, we can use the IComThreadingInfo interface to efficiently determine whether we should pump or not.<span style="mso-spacerun: yes">&nbsp; </span>But if we are on a downlevel platform, we would have to call CoInitialize prior to each blocking operation and check for a failure code to absolutely determine the current state of the thread.<span style="mso-spacerun: yes">&nbsp; </span>This is totally impractical from a performance point of view.<span style="mso-spacerun: yes">&nbsp; </span>So instead we cache what we believe is the correct apartment state of the thread.<span style="mso-spacerun: yes">&nbsp; </span>If the application performs a CoInitialize or CoUninitialize without informing us, then our cached knowledge is stale.<span style="mso-spacerun: yes">&nbsp; </span>So on downlevel platforms we might neglect to pump an STA (which can cause deadlocks).<span style="mso-spacerun: yes">&nbsp; </span>Or we may attempt to pump an MTA (which can cause deadlocks).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Incidentally, if you ever run managed applications under a diagnostic tool like AppVerifier, you may see complaints from that tool at process shutdown that we have leaked one or more CoInitialize calls.<span style="mso-spacerun: yes">&nbsp; </span>In a well-behaved application, each CoInitialize would have a balancing CoUninitialize.<span style="mso-spacerun: yes">&nbsp; </span>However, most processes are not so well-behaved.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s typical for applications to terminate the process without unwinding all the threads of the process.<span style="mso-spacerun: yes">&nbsp; </span>There&#8217;s a very detailed description of the CLR&#8217;s shutdown behavior at </font>http://blogs.msdn.com/cbrumme/archive/2003/08/20/51504.aspx <font face=Tahoma size=2>.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The bottom line here is that the CLR is heavily dependent on knowing exactly when apartments are created and destroyed, or when threads become associated or disassociated with those apartments.<span style="mso-spacerun: yes">&nbsp; </span>But the CLR is largely out of the loop when these operations occur, unless they occur through managed APIs.<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, we are rarely informed.<span style="mso-spacerun: yes">&nbsp; </span>For an extreme example of this, the Shell has APIs which require an STA.<span style="mso-spacerun: yes">&nbsp; </span>If the calling thread is implicitly in the MTA, these Shell APIs CoInitialize that calling thread into an STA.<span style="mso-spacerun: yes">&nbsp; </span>As the call returns, the API will CoUnitialize and rip down the apartment.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We would like to do better here over time.<span style="mso-spacerun: yes">&nbsp; </span>But there are some pretty deep problems and most solutions end up breaking an important scenario here or there.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b><font size=2></font><font face=Tahoma>Back to Pumping<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Enough of the CoInitialize mess.<span style="mso-spacerun: yes">&nbsp; </span>I mentioned above that managed blocking will perform some pumping when called on an STA thread.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Managed blocking includes a contentious Monitor.Enter, WaitHandle.WaitOne, WaitHandle.WaitAny, GC.WaitForPendingFinalizers, our ReaderWriterLock and Thread.Join.<span style="mso-spacerun: yes">&nbsp; </span>It also includes anything else in FX that calls down to these routines.<span style="mso-spacerun: yes">&nbsp; </span>One noticeable place where this happens is during COM Interop.<span style="mso-spacerun: yes">&nbsp; </span>There are pathways through COM Interop where a cache miss occurs on finding an appropriate pUnk to dispatch a call.<span style="mso-spacerun: yes">&nbsp; </span>At those points, the COM call is forced down a slow path and we use this as an opportunity to pump a little bit.<span style="mso-spacerun: yes">&nbsp; </span>We do this to allow the Finalizer thread to release any pUnks on the current STA, if the application is neglecting to pump.<span style="mso-spacerun: yes">&nbsp; </span>(Remember those ASP Compat and Console client scenarios?)<span style="mso-spacerun: yes">&nbsp; </span>This is a questionable practice on our part.<span style="mso-spacerun: yes">&nbsp; </span>It causes reentrancy at a place where it normally could never occur in pure unmanaged scenarios.<span style="mso-spacerun: yes">&nbsp; </span>But it allows a number of applications to successfully run without clogging up the Finalizer thread. </font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway, managed blocking does not include PInvokes directly to any of the OS blocking services.<span style="mso-spacerun: yes">&nbsp; </span>And keep in mind that if you PInvoke to the OS blocking services directly, the CLR will no longer be able to take control of your thread.<span style="mso-spacerun: yes">&nbsp; </span>Operations like Thread.Interrupt, Thread.Abort and AppDomain.Unload will be indefinitely delayed.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Did you notice that I neglected to mention WaitHandle.WaitAll in the list of managed blocking opeprations?<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because we don&#8217;t allow you to call WaitAll from an STA thread.<span style="mso-spacerun: yes">&nbsp; </span>The reason is rather subtle.<span style="mso-spacerun: yes">&nbsp; </span>When you perform a pumping wait, at some level you need to call MsgWaitForMultipleObjectsEx, or a similar Msg* based variant.<span style="mso-spacerun: yes">&nbsp; </span>But the semantics of a WAIT_ALL on an OS MsgWaitForMultipleObjectsEx call is rather surprising and not what you want at all.<span style="mso-spacerun: yes">&nbsp; </span>It waits for all the handles to be signaled AND for a message to arrive at the message queue.<span style="mso-spacerun: yes">&nbsp; </span>In other words, all your handles could be signaled and the application will keep blocking until you nudge the mouse!<span style="mso-spacerun: yes">&nbsp; </span>Ugh.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We&#8217;ve toyed with some workarounds for this case.<span style="mso-spacerun: yes">&nbsp; </span>For example, you could imagine spinning up an MTA thread and having it perform the blocking operation on the handles.<span style="mso-spacerun: yes">&nbsp; </span>When all the handles are signaled, it could set another event.<span style="mso-spacerun: yes">&nbsp; </span>The STA thread would do a WaitHandle.WaitOne on that other event.<span style="mso-spacerun: yes">&nbsp; </span>This gives us the desired behavior that the STA thread wakes up when all handles are signaled, and it still pumps the message queue.<span style="mso-spacerun: yes">&nbsp; </span>However, if any of those handles are &#8220;thread-owned&#8221;, like a Mutex, then we have broken the semantics.<span style="mso-spacerun: yes">&nbsp; </span>Our sacrificial MTA thread now owns the Mutex, rather than the STA thread.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Another technique would be to put the STA thread into a loop.<span style="mso-spacerun: yes">&nbsp; </span>Each iteration would ping the handles with a brief timeout to see if it could acquire them.<span style="mso-spacerun: yes">&nbsp; </span>Then it would check the message queue with a PeekMessage or similar technique, and then iterate.<span style="mso-spacerun: yes">&nbsp; </span>This is a terrible solution for battery-powered devices or for Terminal Server scenarios.<span style="mso-spacerun: yes">&nbsp; </span>What used to be efficient blocking is now busily spinning in a loop.<span style="mso-spacerun: yes">&nbsp; </span>And if no messages actually arrive, we have disturbed the fairness guarantees of the OS blocking primitives by pinging.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>A final technique would be to acquire the handles one by one, using WaitOne.<span style="mso-spacerun: yes">&nbsp; </span>This is probably the worst approach of all.<span style="mso-spacerun: yes">&nbsp; </span>The semantics of an OS WAIT_ALL are that you will either get no handles or you will get all of them.<span style="mso-spacerun: yes">&nbsp; </span>This is critical to avoiding deadlocks, if different parts of the application block on the same set of handles &#8211; but fill the array of handles in random order.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I keep saying that managed blocking will perform &#8220;some pumping&#8221; when called on an STA thread.<span style="mso-spacerun: yes">&nbsp; </span>Wouldn&#8217;t it be great to know exactly what will get pumped?<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, pumping is a black art which is beyond mortal comprehension.<span style="mso-spacerun: yes">&nbsp; </span>On Win2000 and up, we simply delegate to OLE32&#8217;s CoWaitForMultipleHandles service.<span style="mso-spacerun: yes">&nbsp; </span>And before we wrote the initial cut of our pumping code for NT4 and Win9X, I thought I would glance through CoWaitForMultipleHandles to see how it is done.<span style="mso-spacerun: yes">&nbsp; </span>It is many, many pages of complex code.<span style="mso-spacerun: yes">&nbsp; </span>And it uses special flags and APIs that aren&#8217;t even available on Win9X.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The code we finally wrote for the downlevel platforms is relatively simple.<span style="mso-spacerun: yes">&nbsp; </span>We gather the list of hidden OLE windows associated with the current STA thread and try to restrict our pumping to the COM calls which travel through them.<span style="mso-spacerun: yes">&nbsp; </span>However, a lot of the pumping complexity is in USER32 services like PeekMessage.<span style="mso-spacerun: yes">&nbsp; </span>Did you know that calling PeekMessage for one window will actually cause SendMessages to be dispatched on other windows belonging to the same thread?<span style="mso-spacerun: yes">&nbsp; </span>This is another example of how someone made a tradeoff between reentrancy and deadlocks.<span style="mso-spacerun: yes">&nbsp; </span>In this case, the tradeoff was made in favor of reentrancy by someone inside USER32.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>By now you may be thinking &#8220;Okay.<span style="mso-spacerun: yes">&nbsp; </span>Pump more and I get reentrancy.<span style="mso-spacerun: yes">&nbsp; </span>Pump less and I get deadlocks.&#8221;<span style="mso-spacerun: yes">&nbsp; </span>But of course the world is more complicated than that.<span style="mso-spacerun: yes">&nbsp; </span>For instance, the Finalizer thread may synchronously call into the main GUI STA thread, perhaps to release a pUnk there, as we have seen.<span style="mso-spacerun: yes">&nbsp; </span>The causality from the Finalizer thread to the main GUI STA thread is invisible to the CLR (though the CLR Security Lead recently suggested using OLE channel hooks as a technique for making this causality visible).<span style="mso-spacerun: yes">&nbsp; </span>If the main GUI STA thread now calls GC.WaitForPendingFinalizers in order to pump, there&#8217;s a possibility of a deadlock.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because the GUI STA thread must wait for the Finalizer thread to drain its queue.<span style="mso-spacerun: yes">&nbsp; </span>But the Finalizer thread cannot drain its queue until the GUI thread has serviced its incoming synchronous call from the Finalizer.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b><font size=2></font><font face=Tahoma>Reentrancy, Avalon, Longhorn and the Client<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Ah, reentrancy again.<span style="mso-spacerun: yes">&nbsp; </span>From time to time, customers inside or outside the company discover that we are pumping messages during managed blocking on an STA.<span style="mso-spacerun: yes">&nbsp; </span>This is a legitimate concern, because they know that it&#8217;s very hard to write code that&#8217;s robust in the face of reentrancy.<span style="mso-spacerun: yes">&nbsp; </span>In fact, one internal team completely avoids managed blocking, including almost any use of FX, for this reason.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Avalon was very upset, too.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;m not sure how much detail they have disclosed about their threading model.<span style="mso-spacerun: yes">&nbsp; </span>And it&#8217;s certainly not my place to reveal what they are doing.<span style="mso-spacerun: yes">&nbsp; </span>Suffice it to say that their model is an explicit rental model that does not presume thread affinity.<span style="mso-spacerun: yes">&nbsp; </span>If you&#8217;ve read this far, I&#8217;m sure you approve of their decision.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Avalon must necessarily coexist with STAs, but Avalon doesn&#8217;t want to require them.<span style="mso-spacerun: yes">&nbsp; </span>The CLR and Avalon have a shared long term goal of driving STAs out of the platform.<span style="mso-spacerun: yes">&nbsp; </span>But, realistically, this will take decades.<span style="mso-spacerun: yes">&nbsp; </span>Avalon&#8217;s shorter term goal is to allow some useful GUI applications to be written without STAs.<span style="mso-spacerun: yes">&nbsp; </span>Even this is quite difficult.<span style="mso-spacerun: yes">&nbsp; </span>If you call the clipboard today, you will have an STA.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Avalon also has made a conscious design choice to favor deadlocks over reentrancy.<span style="mso-spacerun: yes">&nbsp; </span>In my opinion, this is an excellent goal.<span style="mso-spacerun: yes">&nbsp; </span>Deadlocks are easily debugged.<span style="mso-spacerun: yes">&nbsp; </span>Reentrancy is almost impossible to debug.<span style="mso-spacerun: yes">&nbsp; </span>Instead, it results in odd inconsistencies that manifest over time.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In order to achieve their design goals, Avalon requires the ability to control the CLR&#8217;s pumping. <span style="mso-spacerun: yes">&nbsp;</span>And since we&#8217;ve had similar requests from other teams inside and outside the company, this is a reasonable feature for us to provide.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>V1 of the CLR had a conscious goal of making as much legacy VB and C++ code work as was possible.<span style="mso-spacerun: yes">&nbsp; </span>When we saw the number of applications that failed to pump, we had no choice but to insert pumping for them &#8211; even at the cost of reentrancy.<span style="mso-spacerun: yes">&nbsp; </span>Avalon is in a completely different position.<span style="mso-spacerun: yes">&nbsp; </span>All Avalon code is new code.<span style="mso-spacerun: yes">&nbsp; </span>They are in a great position to define an explicit model for pumping, and then require that all new applications rigorously conform to that model.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Indeed, as much as I dislike STAs, I have a bigger concern about Longhorn and its client focus.<span style="mso-spacerun: yes">&nbsp; </span>Historically, Microsoft has built a ton of great functionality and added it to the platform.<span style="mso-spacerun: yes">&nbsp; </span>But that functionality is often mixed up with various client assumptions.<span style="mso-spacerun: yes">&nbsp; </span>STAs are probably the biggest of those assumptions.<span style="mso-spacerun: yes">&nbsp; </span>The Shell is an example of this.<span style="mso-spacerun: yes">&nbsp; </span>It started out as a user-focused set of services, like the namespace.<span style="mso-spacerun: yes">&nbsp; </span>But it&#8217;s growing into something that&#8217;s far more generally useful.<span style="mso-spacerun: yes">&nbsp; </span>To the extent that the Shell wants to take its core concepts and make them part of the base managed Longhorn platform, it needs to shed the client focus.<span style="mso-spacerun: yes">&nbsp; </span>The same is true of Office.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>For instance, I want to write some code that navigates to a particular document through some namespace and then processes it in some manner.<span style="mso-spacerun: yes">&nbsp; </span>And I want that exact same code to run correctly on the client and on the server.<span style="mso-spacerun: yes">&nbsp; </span>On the client, my processing of that document should not make the UI unresponsive.<span style="mso-spacerun: yes">&nbsp; </span>On the server, my processing of that document should not cause problems with scalability or throughput.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Historically, this just hasn&#8217;t been the case.<span style="mso-spacerun: yes">&nbsp; </span>We have an opportunity to correct this problem once, with the major rearchitecture that is Longhorn.<span style="mso-spacerun: yes">&nbsp; </span>But although Longhorn will have both client and server releases, I worry that we might still have a dangerous emphasis on the client.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This may be one of the biggest risks we face in Longhorn.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b><font size=2></font><font face=Tahoma>Winding Down<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Finally, I feel a little bad about picking something I don&#8217;t like and writing about it.<span style="mso-spacerun: yes">&nbsp; </span>But there&#8217;s a reason that this topic came up.<span style="mso-spacerun: yes">&nbsp; </span>Last week, a customer in <st1 :country-region w:st="on"></st1><st1 :place w:st="on">Japan</st1> was struggling with using mshtml.dll to crack some HTML files from inside ASP.NET.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s the obvious thing to do.<span style="mso-spacerun: yes">&nbsp; </span>Clearly &#8216;mshtml&#8217; stands for Microsoft HTML and clearly this is how we expect customers to process files in this format.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Unfortunately, MSHTML was written as client-side functionality.<span style="mso-spacerun: yes">&nbsp; </span>In fact, I&#8217;m told that it drives its own initialization by posting Windows messages back to itself and waiting for them to be pumped.<span style="mso-spacerun: yes">&nbsp; </span>So if you aren&#8217;t pumping an STA, you aren&#8217;t going to get very far.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There&#8217;s that disturbing historical trend at Microsoft to combine generally useful functionality with a client bias again!</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We explained to the customer the risks of using client components on a server, and the pumping behavior that is inherent in managed blocking on an STA.<span style="mso-spacerun: yes">&nbsp; </span>After we had been through all the grisly details, the customer made the natural observation:<span style="mso-spacerun: yes">&nbsp; </span>None of this is written down anywhere.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Well, I still never talked about a mysterious new flag to CoWaitForMultipleHandles.<span style="mso-spacerun: yes">&nbsp; </span>Or how custom implementations of IMessageFilter can cause problems.<span style="mso-spacerun: yes">&nbsp; </span>Or the difference between <st1 :place w:st="on">Main</st1> and Single. <span style="mso-spacerun: yes">&nbsp;</span>Or the relationship between apartments and COM+ contexts and ServicedComponents.<span style="mso-spacerun: yes">&nbsp; </span>Or the amazing discovery that OLE32 sometimes requires you to pump the MTA if you have DCOM installed on Win9X.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But I&#8217;m sure that at this point I&#8217;ve said far more than most people care to hear about this subject. </font></p>
<img src="http://blogs.msdn.com/aggbug.aspx?PostID=66219" width="1" height="1"/><br />
<span style="font-size:8pt; font-style:italic">http://blogs.msdn.com/cbrumme/archive/2004/02/02/66219.aspx</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/25/apartments-and-pumping-in-the-clr/feed/</wfw:commentRss>
	</item>
		<item>
		<title>Natural Sorting in C#</title>
		<link>http://cahtter.blogsome.com/2008/03/25/natural-sorting-in-c/</link>
		<comments>http://cahtter.blogsome.com/2008/03/25/natural-sorting-in-c/#comments</comments>
		<pubDate>Tue, 25 Mar 2008 10:48:14 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/25/natural-sorting-in-c/</guid>
		<description><![CDATA[	Also see: Debugging an InvalidCastException
	Jeff Atwood recently posted about natural sorting. This is all about making sure that strings that contain numbers sort numerically. I’m slightly surprised to see that he wants to call it alphabetical sorting. Surely by definition, alphabetical sorting is defined by, well, the alphabet. This is an issue about numbers, not [...]]]></description>
			<content:encoded><![CDATA[	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/23/debugging-an-invalidcastexception/"  title="Debugging an InvalidCastException">Debugging an InvalidCastException</a></i></p>
	<p>Jeff Atwood recently posted about natural sorting. This is all about making sure that strings that contain numbers sort numerically. I’m slightly surprised to see that he wants to call it alphabetical sorting. Surely by definition, alphabetical sorting is defined by, well, the alphabet. This is an issue about numbers, not letters.</p>
	<p>Anyway, he says he tried and gave up on a succinct C# version. He suggests that it will take 40+ lines of code. I believe that’s misleading, because as far as I can tell, the Python versions are only able to be so succinct because Python already appears to know how to sort an array. Both examples he shows rely on this. In.NET, collections aren’t intrinsically sortable. Let’s sort that:</p>
	<pre><span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;summary&gt;</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> Compares two sequences.</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;/summary&gt;</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;typeparam name=&#8221;T&#8221;&gt;</span><span style=\"color:green\">Type of item in the sequences.</span><span style=\"color:808080\">&lt;/typeparam&gt;</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;remarks&gt;</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> Compares elements from the two input sequences in turn. If we</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> run out of list before finding unequal elements, then the shorter</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> list is deemed to be the lesser list.</span>
<span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;/remarks&gt;</span>
<span style=\"color:blue\">public</span> <span style=\"color:blue\">class</span> <span style=\"color:dimgray\">EnumerableComparer</span>&lt;T&gt; : <span style=\"color:dimgray\">IComparer</span>&lt;<span style=\"color:dimgray\">IEnumerable</span>&lt;T&gt;&gt;
{
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;summary&gt;</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> Create a sequence comparer using the default comparer for T.</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;/summary&gt;</span>
 <span style=\"color:blue\">public</span> EnumerableComparer()
 {
 comp = <span style=\"color:dimgray\">Comparer</span>&lt;T&gt;.Default;
 }
	
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;summary&gt;</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> Create a sequence comparer, using the specified item comparer</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> for T.</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;/summary&gt;</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;param name=&#8221;comparer&#8221;&gt;</span><span style=\"color:green\">Comparer for comparing each pair of</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> items from the sequences.</span><span style=\"color:808080\">&lt;/param&gt;</span>
 <span style=\"color:blue\">public</span> EnumerableComparer(<span style=\"color:dimgray\">IComparer</span>&lt;T&gt; comparer)
 {
 comp = comparer;
 }
	
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;summary&gt;</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> Object used for comparing each element.</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;/summary&gt;</span>
 <span style=\"color:blue\">private</span> <span style=\"color:dimgray\">IComparer</span>&lt;T&gt; comp;
	
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;summary&gt;</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> Compare two sequences of T.</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;/summary&gt;</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;param name=&#8221;x&#8221;&gt;</span><span style=\"color:green\">First sequence.</span><span style=\"color:808080\">&lt;/param&gt;</span>
 <span style=\"color:808080\">///</span><span style=\"color:green\"> </span><span style=\"color:808080\">&lt;param name=&#8221;y&#8221;&gt;</span><span style=\"color:green\">Second sequence.</span><span style=\"color:808080\">&lt;/param&gt;</span>
 <span style=\"color:blue\">public</span> <span style=\"color:blue\">int</span> Compare(<span style=\"color:dimgray\">IEnumerable</span>&lt;T&gt; x, <span style=\"color:dimgray\">IEnumerable</span>&lt;T&gt; y)
 {
 <span style=\"color:blue\">using</span> (<span style=\"color:dimgray\">IEnumerator</span>&lt;T&gt; leftIt = x.GetEnumerator())
 <span style=\"color:blue\">using</span> (<span style=\"color:dimgray\">IEnumerator</span>&lt;T&gt; rightIt = y.GetEnumerator())
 {
 <span style=\"color:blue\">while</span> (<span style=\"color:blue\">true</span>)
 {
 <span style=\"color:blue\">bool</span> left = leftIt.MoveNext();
 <span style=\"color:blue\">bool</span> right = rightIt.MoveNext();
	
 <span style=\"color:blue\">if</span> (!(left || right)) <span style=\"color:blue\">return</span> 0;
	
 <span style=\"color:blue\">if</span> (!left) <span style=\"color:blue\">return</span> -1;
 <span style=\"color:blue\">if</span> (!right) <span style=\"color:blue\">return</span> 1;
	
 <span style=\"color:blue\">int</span> itemResult = comp.Compare(leftIt.Current, rightIt.Current);
 <span style=\"color:blue\">if</span> (itemResult != 0) <span style=\"color:blue\">return</span> itemResult;
 }
 }
 }
}
	</pre>
	<p><a id="more-30"></a>
<p>(Note: I offer the code samples on this page under the MIT license.)</p>
	<p>So yes, I need a lot of code. However, that’s a utility class that is applicable to a wide range of scenarios, not just this one. It’s slightly irritating that it’s not already built into the.NET framework. Heck, maybe it is, and I’ve just been looking in the wrong place.</p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/link-love-09212007/"  title="Link Love: 09/21/2007">Link Love: 09/21/2007</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/25/sometimes-its-the-small-things/"  title="Sometimes, it's the small things..">Sometimes, it&#8217;s the small things..</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://simma1990.edublogs.org/2008/03/23/vsnet-macro-to-group-and-sort-your-using-statements/"  title="VS.NET Macro To Group and Sort Your Using Statements">VS.NET Macro To Group and Sort Your Using Statements</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/link-love-09212007/"  title="Link Love: 09/21/2007">Link Love: 09/21/2007</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/silverlight-2-beta-1-cross-domain-bug/"  title="Silverlight 2 Beta 1 Cross Domain Bug">Silverlight 2 Beta 1 Cross Domain Bug</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://simma1990.edublogs.org/2008/03/23/tagspace-meet-claimspace/"  title="Tagspace, Meet Claimspace">Tagspace, Meet Claimspace</a></i></p>
	<p>Given easy way to compare two sequences, a C# 3.0 natural sort becomes roughly as trivial as the Python examples in Jeff’s blog:</p>
	<pre><span style=\"color:blue\">string</span>[] testItems = { <span style=\"color:brown\">&#8220;z24&#8243;</span>, <span style=\"color:brown\">&#8220;z2&#8243;</span>, <span style=\"color:brown\">&#8220;z15&#8243;</span>, <span style=\"color:brown\">&#8220;z1&#8243;</span>,
 <span style=\"color:brown\">&#8220;z3&#8243;</span>, <span style=\"color:brown\">&#8220;z20&#8243;</span>, <span style=\"color:brown\">&#8220;z5&#8243;</span>, <span style=\"color:brown\">&#8220;z11&#8243;</span>,
 <span style=\"color:brown\">&#8220;z 21&#8243;</span>, <span style=\"color:brown\">&#8220;z22&#8243;</span> };
	
<span style=\"color:dimgray\">Func</span>&lt;<span style=\"color:blue\">string</span>, <span style=\"color:blue\">object</span>&gt; convert = str =&gt;
{ <span style=\"color:blue\">try</span> { <span style=\"color:blue\">return</span> <span style=\"color:blue\">int</span>.Parse(str); }
 <span style=\"color:blue\">catch</span> { <span style=\"color:blue\">return</span> str; } };
<span style=\"color:blue\">var</span> sorted = testItems.OrderBy(
 str =&gt; <span style=\"color:dimgray\">Regex</span>.Split(str.Replace(<span style=\"color:brown\">&#8221; &#8220;</span>, <span style=\"color:brown\">&#8220;&#8221;</span>), <span style=\"color:brown\">&#8220;([0-9]+)&#8221;</span>).Select(convert),
 <span style=\"color:blue\">new</span> <span style=\"color:dimgray\">EnumerableComparer</span>&lt;<span style=\"color:blue\">object</span>&gt;());
</pre>
	<p>It’s probably not meaningful to count lines of code. This being C#, I could have put it all on one line. As it is, I split it across more lines than I normally would, to avoid an annoying HTML layout issue. (I put my code samples in <code>PRE</code> blocks to get the formatting right, <code>PRE</code> blocks and long lines are a bad combination.) But I think it’s fair to say that any differences in size are due merely to syntactic differences between Python and C#. Structurally, there’s no substantial difference – I’ve been able to apply exactly the same techniques the Python examples used in C#.</p>
	<div class="interline"><a href="http://www.jbTop.com/" title="Live Person">Live Person</a>: Live Chat Solution for Online Customer Service on Website.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://simma1990.edublogs.org/2008/03/24/devweek-2008-silverlight-precon-demos/"  title="DevWeek 2008 Silverlight Precon Demos">DevWeek 2008 Silverlight Precon Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/25/life-calculus/"  title="Life Calculus">Life Calculus</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/24/the-pdc-and-application-compatibility-but-still-no-hosting/"  title="The PDC and Application Compatibility, but still no Hosting">The PDC and Application Compatibility, but still no Hosting</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://simma1990.edublogs.org/2008/03/24/jsr-203-more-new-io-apis-nio2/"  title="JSR-203 more New I/O APIs - NIO.2">JSR-203 more New I/O APIs - NIO.2</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/java-design-operator-overloading-and-people/"  title="Java design, operator overloading and people">Java design, operator overloading and people</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://simma1990.edublogs.org/2008/03/22/updated-finalization-and-hosting/"  title="Updated Finalization and Hosting">Updated Finalization and Hosting</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/22/snippet-compiler-update/"  title="Snippet Compiler update">Snippet Compiler update</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/24/interested-in-artificial-intelligence-what-about-wikis-well-now-you-can-have-both/"  title="Interested in Artificial Intelligence? What about Wiki's? Well, now you can have both.">Interested in Artificial Intelligence? What about Wiki&#8217;s? Well, now you can have both.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://simma1990.edublogs.org/2008/03/22/sometimes-its-the-small-things/"  title="Sometimes, it's the small things..">Sometimes, it&#8217;s the small things..</a></i></p>
	<p>If I print out the results using this code:</p>
	<pre><span style=\"color:blue\">foreach</span> (<span style=\"color:blue\">string</span> s <span style=\"color:blue\">in</span> sorted)
{
 <span style=\"color:dimgray\">Console</span>.WriteLine(s);
}
</pre>
	<p>It prints out the test items in this order:</p>
	<pre>z1
z2
z3
z5
z11
z15
z20
z 21
z22
z24
</pre>
	<p>I.e., ascending numeric order, rather than what you’d get with most string ordering.</p>
	<p>[<b>Updated 21st December 2007</b>: Charles Petzold didn’t like the original version, which treated spaces as significant for sorting. So I’ve updated the example to ignore spaces, as the position of “z 21” in the output above shows. I simply added a call to <code>Replace(" ", "")</code> on the string before passing it into <code>Regex.Split</code>.]</p>
<br />
<span style="font-size:8pt; font-style:italic">http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/25/natural-sorting-in-c/feed/</wfw:commentRss>
	</item>
		<item>
		<title>Updated Finalization and Hosting</title>
		<link>http://cahtter.blogsome.com/2008/03/25/updated-finalization-and-hosting/</link>
		<comments>http://cahtter.blogsome.com/2008/03/25/updated-finalization-and-hosting/#comments</comments>
		<pubDate>Tue, 25 Mar 2008 03:00:02 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/25/updated-finalization-and-hosting/</guid>
		<description><![CDATA[	Also see: Memory Model
	My original posts on Finalization and Hosting had some hokey XXXXX markers in place of content, where that content hadn&#8217;t already been disclosed in some form.&nbsp; Now that the Visual Studio 2005 Community Preview is available, I&#8217;ve gone back to those two posts and replaced the XXXXX markers with real text.
	Also, it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p>My original posts on Finalization and Hosting had some hokey XXXXX markers in place of content, where that content hadn&#8217;t already been disclosed in some form.&nbsp; Now that the Visual Studio 2005 Community Preview is available, I&#8217;ve gone back to those two posts and replaced the XXXXX markers with real text.</p>
	<p>Also, it&#8217;s obviously been a while since my last post.&nbsp; I started writing something this weekend, but the weather here has been spectacular and I was compelled to go outside and play.&nbsp; I&#8217;ll try to have something in the next couple of weeks.</p>
	<p>&nbsp;</p>
<img src="http://blogs.msdn.com/aggbug.aspx?PostID=120609" width="1" height="1"/><br />
<span style="font-size:8pt; font-style:italic">http://blogs.msdn.com/cbrumme/archive/2004/04/26/120609.aspx</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/25/updated-finalization-and-hosting/feed/</wfw:commentRss>
	</item>
		<item>
		<title>Startup, Shutdown and related matters</title>
		<link>http://cahtter.blogsome.com/2008/03/24/startup-shutdown-and-related-matters/</link>
		<comments>http://cahtter.blogsome.com/2008/03/24/startup-shutdown-and-related-matters/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 20:00:13 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/24/startup-shutdown-and-related-matters/</guid>
		<description><![CDATA[	Also see: Single source code base for Silverlight and WPF solutions
	Usually
I write blog articles on topics that people request via email or comments on
other blogs.&nbsp; Well, nobody has ever
asked me to write anything about shutdown.
	
	But then
I look at all the problems that occur during process shutdown in the unmanaged
world.&nbsp; These problems occur because
many people don’t [...]]]></description>
			<content:encoded><![CDATA[	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/single-source-code-base-for-silverlight-and-wpf-solutions/"  title="Single source code base for Silverlight and WPF solutions">Single source code base for Silverlight and WPF solutions</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Usually<br />
I write blog articles on topics that people request via email or comments on<br />
other blogs.<span style="mso-spacerun: yes">&nbsp; </span>Well, nobody has ever<br />
asked me to write anything about shutdown.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But then<br />
I look at all the problems that occur during process shutdown in the unmanaged<br />
world.<span style="mso-spacerun: yes">&nbsp; </span>These problems occur because<br />
many people don’t understand the rules, or they don’t follow the rules, or the<br />
rules couldn’t possibly work anyway.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We’ve<br />
taken a somewhat different approach for managed applications.<span style="mso-spacerun: yes">&nbsp; </span>But I don’t think we’ve ever explained<br />
in detail what that approach is, or how we expect well-written applications to<br />
survive an orderly shutdown.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Furthermore, managed applications still execute within an unmanaged OS<br />
process, so they are still subject to the OS rules.<span style="mso-spacerun: yes">&nbsp; </span>And in V1 and V1.1 of the CLR we’ve<br />
horribly violated some of those OS rules related to startup and shutdown.<span style="mso-spacerun: yes">&nbsp; </span>We’re trying to improve our behavior<br />
here, and I’ll discuss that too.</font></p>
	<p><a id="more-28"></a><br />
<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/a-web-site-is-not-an-rss-feednor-the-reverse/"  title="A web site is not an RSS feed...nor the reverse.">A web site is not an RSS feed&#8230;nor the reverse.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/the-internet-is-officially-dead-boring-its-the-economy-stupid/"  title="The Internet is Officially Dead &amp; Boring - Its the economy stupid !">The Internet is Officially Dead &amp; Boring - Its the economy stupid !</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/a-web-site-is-not-an-rss-feednor-the-reverse/"  title="A web site is not an RSS feed...nor the reverse.">A web site is not an RSS feed&#8230;nor the reverse.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/be-my-support-group/"  title="Be my Support Group">Be my Support Group</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/mix-08-sessions-published/"  title="Mix 08 Sessions Published">Mix 08 Sessions Published</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/a-web-site-is-not-an-rss-feednor-the-reverse/"  title="A web site is not an RSS feed...nor the reverse.">A web site is not an RSS feed&#8230;nor the reverse.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/cool-silverlight-momentum-video-posted/"  title="Cool Silverlight Momentum Video Posted">Cool Silverlight Momentum Video Posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/cool-silverlight-momentum-video-posted/"  title="Cool Silverlight Momentum Video Posted">Cool Silverlight Momentum Video Posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/aspnet-mvc-in-codeplex-and-extensible-unit-testing/"  title="ASP.NET MVC in CodePlex and Extensible Unit Testing">ASP.NET MVC in CodePlex and Extensible Unit Testing</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Questionable<br />
APIs<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Unfortunately, I can’t discuss the model for shutting down managed<br />
applications without first discussing how unmanaged applications terminate.<span style="mso-spacerun: yes">&nbsp; </span>And, as usual, I’ll go off on a bunch of<br />
wild tangents.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Ultimately, every OS process shuts down via a call to ExitProcess or<br />
TerminateProcess.<span style="mso-spacerun: yes">&nbsp; </span>ExitProcess is<br />
the nice orderly shutdown, which notifies each DLL of the termination.<span style="mso-spacerun: yes">&nbsp; </span>TerminateProcess is ruder, in that the<br />
DLLs are not informed.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
relationship between ExitProcess and TerminateProcess has a parallel in the<br />
thread routines ExitThread and TerminateThread.<span style="mso-spacerun: yes">&nbsp; </span>ExitThread is the nice orderly thread<br />
termination, whereas if you ever call TerminateThread you may as well kill the<br />
process.<span style="mso-spacerun: yes">&nbsp; </span>It’s almost guaranteed to<br />
be in a corrupt state.<span style="mso-spacerun: yes">&nbsp; </span>For example,<br />
you may have terminated the thread while it holds the lock for the OS heap.<span style="mso-spacerun: yes">&nbsp; </span>Any thread attempting to allocate or<br />
release memory from that same heap will now block forever.</font></p>
	<div class="interline">Multisoft Group: <a href="http://www.multisoftgroup.com/skills.html" title="Custom software solutions">Custom software solutions</a> for your business.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/mix-08-sessions-published/"  title="Mix 08 Sessions Published">Mix 08 Sessions Published</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/music-and-movies-give-away-the-soundtrack/"  title="Music and Movies - Give Away the Soundtrack">Music and Movies - Give Away the Soundtrack</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/exception-handling-in-running-a-business/"  title="Exception Handling in Running a Business">Exception Handling in Running a Business</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/quaker-votes/"  title="Quaker votes">Quaker votes</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/music-and-movies-give-away-the-soundtrack/"  title="Music and Movies - Give Away the Soundtrack">Music and Movies - Give Away the Soundtrack</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/exception-handling-in-running-a-business/"  title="Exception Handling in Running a Business">Exception Handling in Running a Business</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/link-love-09212007/"  title="Link Love: 09/21/2007">Link Love: 09/21/2007</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/nhl-seven-days-a-week/"  title="NHL seven days a week">NHL seven days a week</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/microformats-are-like-rfid-tags-for-the-web/"  title="Microformats are like RFID tags for the Web">Microformats are like RFID tags for the Web</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Realistically, Win32 shouldn’t contain a TerminateThread service.<span style="mso-spacerun: yes">&nbsp; </span>To a first approximation, anyone who has<br />
ever used this service has injected a giant bug into his application.<span style="mso-spacerun: yes">&nbsp; </span>But it’s too late to remove it<br />
now.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In that<br />
sense, TerminateThread is like System.Threading.Thread.Suspend and Resume.<span style="mso-spacerun: yes">&nbsp; </span>I cannot justify why I added those<br />
services.<span style="mso-spacerun: yes">&nbsp; </span>The OS SuspendThread and<br />
ResumeThread are extremely valuable to a tiny subset of applications.<span style="mso-spacerun: yes">&nbsp; </span>The CLR itself uses these routines to<br />
take control of threads for purposes like Garbage Collection and – as we’ll see<br />
later – for process shutdown.<span style="mso-spacerun: yes">&nbsp; </span>As<br />
with TerminateThread, there’s a significant risk of leaving a thread suspended<br />
at a “bad” spot.<span style="mso-spacerun: yes">&nbsp; </span>If you call<br />
SuspendThread while a thread is inside the OS heap lock, you better not try to<br />
allocate or free from that same heap.<span style="mso-spacerun: yes">&nbsp;<br />
</span>In a similar fashion, if you call SuspendThread while a thread holds the<br />
OS loader lock (e.g. while the thread is executing inside DllMain) then you<br />
better not call LoadLibrary, GetProcAddress, GetModuleHandle, or any of the other OS<br />
services that require that same lock.</font></p>
	<div class="interline"><a href="http://www.jbTop.com/" title="Live Person">Live Person</a>: Live Chat Solution for Online Customer Service on Website.
</div>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Even<br />
worse, if you call SuspendThread on a thread that is in the middle of exception<br />
dispatching inside the kernel, a subsequent GetThreadContext or SetThreadContext<br />
can actually produce a blend of the register state at the point of the<br />
suspension and the register state that was captured when the exception was<br />
triggered.<span style="mso-spacerun: yes">&nbsp; </span>If we attempt to modify<br />
a thread’s context (perhaps bashing the EIP – on X86 – to redirect the thread’s<br />
execution to somewhere it will synchronize with the GC or other managed<br />
suspension), our update to EIP might quietly get lost.<span style="mso-spacerun: yes">&nbsp; </span>Fortunately it’s possible to coordinate<br />
our user-mode exception dispatching with our suspension attempts in order to<br />
tolerate this race condition.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="mso-spacerun: yes"><font face=Tahoma size=2></font></span>&nbsp;</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>And<br />
probably the biggest gotcha with using the OS SuspendThread &amp; ResumeThread<br />
services is on Win9X.<span style="mso-spacerun: yes">&nbsp; </span>If a Win9X<br />
box contains real-mode device drivers (and yes, some of them still do), then<br />
it’s possible for the hardware interrupt associated with the device to interact<br />
poorly with the thread suspension.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Calls to GetThreadContext can deliver a register state that is perturbed<br />
by the real-mode exception processing.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The CLR installs a VxD on those operating systems to detect this case and<br />
retry the suspension.</font></p>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Person Software">Live Person Software</a>: Turn website visitors into your customers.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/c-30-lambdas-and-type-inference/"  title="C# 3.0 Lambdas and Type Inference">C# 3.0 Lambdas and Type Inference</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/note-to-self-blog-about-using-service-broker/"  title="Note to self: Blog about using Service Broker">Note to self: Blog about using Service Broker</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway,<br />
with sufficient care and discipline it’s possible to use the OS SuspendThread<br />
&amp; ResumeThread to achieve some wonderful things.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But the<br />
managed Thread.Suspend &amp; Resume are harder to justify.<span style="mso-spacerun: yes">&nbsp; </span>They differ from the unmanaged<br />
equivalents in that they only ever suspend a thread at a spot inside managed<br />
code that is “safe for a garbage collection.”<span style="mso-spacerun: yes">&nbsp; </span>In other words, we can report all the GC<br />
references at that spot and we can unwind the stack and register state to reveal<br />
our caller’s execution state.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Because<br />
we are at a place that’s safe for garbage collection, we can be sure that<br />
Thread.Suspend won’t leave a thread suspended while it holds an OS heap<br />
lock.<span style="mso-spacerun: yes">&nbsp; </span>But it may be suspended while<br />
it holds a managed Monitor (‘lock’ in C# or ‘SyncLock’ in VB.NET).<span style="mso-spacerun: yes">&nbsp; </span>Or it may be suspended while it is<br />
executing the class constructor (.cctor) of an important class like<br />
System.String.<span style="mso-spacerun: yes">&nbsp; </span>And over time we<br />
intend to write more of the CLR in managed code, so we can enjoy all the<br />
benefits.<span style="mso-spacerun: yes">&nbsp; </span>When that happens, a<br />
thread might be suspended while loading a class or resolving security policy for<br />
a shared assembly or generating shared VTables for COM Interop.</font></p>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Help Server">Live Help Server</a>: Jerry Messenger Server is Live Chat with Users on your websites.
</div>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The real<br />
problem is that developers sometimes confuse Thread.Suspend with a<br />
synchronization primitive.<span style="mso-spacerun: yes">&nbsp; </span>It is<br />
not.<span style="mso-spacerun: yes">&nbsp; </span>If you want to synchronize two<br />
threads, you should use appropriate primitives like Monitor.Enter,<br />
Monitor.Wait, or WaitHandle.WaitOne.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Of course, it’s harder to use these primitives because you actually have<br />
to write code that’s executed by both threads so that they cooperate<br />
nicely.<span style="mso-spacerun: yes">&nbsp; </span>And you have to eliminate<br />
the race conditions.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’m<br />
already wandering miles away from Shutdown, and I need to get back.<span style="mso-spacerun: yes">&nbsp; </span>But I can’t resist first mentioning that<br />
TerminateThread is distinctly different from the managed Thread.Abort service,<br />
both in terms of our aspirations and in terms of our current<br />
implementation.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Nobody<br />
should ever call TerminateThread.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Ever.</font></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Help Desk Software">Help Desk Software</a>: for your business. Java Custom Software Soulutions and Service.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/devweek-2008-cross-platform-silverlight-demos/"  title="DevWeek 2008 Cross Platform Silverlight Demos">DevWeek 2008 Cross Platform Silverlight Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/mix-08-sessions-published/"  title="Mix 08 Sessions Published">Mix 08 Sessions Published</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/be-my-support-group/"  title="Be my Support Group">Be my Support Group</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfile-vs-loadfrom/"  title="LoadFile vs. LoadFrom">LoadFile vs. LoadFrom</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Today<br />
you can safely call Thread.Abort in two scenarios.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l8 level1 lfo4; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>You can call Abort on your own thread<br />
 (Thread.CurrentThread.Abort()).<span style="mso-spacerun: yes">&nbsp;<br />
 </span>This is not much different than throwing any exception on your thread,<br />
 other than the undeniable manner in which the exception propagates.<span style="mso-spacerun: yes">&nbsp; </span>The propagation is undeniable in the<br />
 sense that your thread will continue to abort, even if you attempt to swallow<br />
 the ThreadAbortException in a catch clause.<span style="mso-spacerun: yes">&nbsp; </span>At the end-catch, the CLR notices that<br />
 an abort is in progress and we re-throw the abort.<span style="mso-spacerun: yes">&nbsp; </span>You must either explicitly call the<br />
 ResetAbort method – which carries a security demand – or the exception must<br />
 propagate completely out of all managed handlers, at which point we reset the<br />
 undeniable nature of the abort and allow unmanaged code to (hopefully) swallow<br />
 it.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=2>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l8 level1 lfo4; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>An Abort is performed on all threads that have stack in an<br />
 AppDomain that is being unloaded.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Since we are throwing away the AppDomain anyway, we can often tolerate<br />
 surprising execution of threads at fairly arbitrary spots in their<br />
 execution.<span style="mso-spacerun: yes">&nbsp; </span>Even if this leaves<br />
 managed locks unreleased and AppDomain statics in an inconsistent state, we’re<br />
 throwing away all that state as part of the unload anyway.<span style="mso-spacerun: yes">&nbsp; </span>This situation isn’t as robust as we<br />
 would like it to be.<span style="mso-spacerun: yes">&nbsp; </span>So we’re<br />
 investing a lot of effort into improving our behavior as part of getting<br />
 “squeaky clean” for highly available execution inside SQL Server in our next<br />
 release.</font></li>
</ol>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Help Desk Software">Help Desk Software</a>: for your business. Java Custom Software Soulutions and Service.
</div>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Longer<br />
term, we’re committed to building enough reliability infrastructure around<br />
Thread.Abort that you can reasonably expect to use it to control threads that<br />
remain completely inside managed code.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Aborting threads that interleave managed and unmanaged execution in a<br />
rich way will always remain problematic, because we are limited in how much we<br />
can control the unmanaged portion of that execution.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>ExitProcess<br />
in a nutshell<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So what<br />
does the OS ExitProcess service actually do?<span style="mso-spacerun: yes">&nbsp; </span>I’ve never read the source code.<span style="mso-spacerun: yes">&nbsp; </span>But based on many hours of stress<br />
investigations, it seems to do the following:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l0 level1 lfo1; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>Kill all the threads except one,<br />
whatever they are doing in user mode.<span style="mso-spacerun: yes">&nbsp;<br />
</span>On NT-based operating systems, the surviving thread is the thread that<br />
called ExitProcess.<span style="mso-spacerun: yes">&nbsp; </span>This becomes<br />
the shutdown thread.<span style="mso-spacerun: yes">&nbsp; </span>On Win9X-based<br />
operating systems, the surviving thread is somewhat random.<span style="mso-spacerun: yes">&nbsp; </span>I suspect that it’s the last thread to<br />
get around to committing suicide.</font></p>
	<div class="interline"><a href="http://www.jbTop.com/" title="Help Desk Software">Help Desk Software</a>: Next generation of Live Chat. Jabber/XMPP Live Chat Service for your website.
</div>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l0 level1 lfo1; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>Once only one thread survives, no<br />
further threads can enter the process… almost.<span style="mso-spacerun: yes">&nbsp; </span>On NT-based systems, I only see<br />
superfluous threads during shutdown if a debugger attaches to the process during<br />
this window.<span style="mso-spacerun: yes">&nbsp; </span>On Win9X-based<br />
systems, any threads that were created during this early phase of shutdown are<br />
permitted to start up.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
DLL_THREAD_ATTACH notifications to DllMain for the starting threads will be<br />
arbitrarily interspersed with the DLL_PROCESS_DETACH notifications to DllMain<br />
for the ensuing shutdown.<span style="mso-spacerun: yes">&nbsp; </span>As you<br />
might expect, this can cause crashes.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l0 level1 lfo1; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>3)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>Since only one thread has survived<br />
(on the more robust NT-based operating systems), the OS now weakens all the<br />
CRITICAL_SECTIONs.<span style="mso-spacerun: yes">&nbsp; </span>This is mixed<br />
blessing.<span style="mso-spacerun: yes">&nbsp; </span>It means that the<br />
shutdown thread can allocate and free objects from the system heap without<br />
deadlocking.<span style="mso-spacerun: yes">&nbsp; </span>And it means that<br />
application data structures protected by application CRITICAL_SECTIONs are<br />
accessible.<span style="mso-spacerun: yes">&nbsp; </span>But it also means that<br />
the shutdown thread can see corrupt application state.<span style="mso-spacerun: yes">&nbsp; </span>If one thread was wacked in step #1<br />
above while it held a CRITICAL_SECTION and left shared data in an inconsistent<br />
state, the shutdown thread will see this inconsistency and must somehow tolerate<br />
it. <span style="mso-spacerun: yes">&nbsp;</span>Also, data structures that are<br />
protected by synchronization primitives other than CRITICAL_SECTION are still<br />
prone to deadlock.</font></p>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Chat Software" >Live Chat (Help Desk) Server Software</a> &#8212;<br />
Improve performance of customer support with Jerry Messenger. Live Chat Support to your website visitors.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l0 level1 lfo1; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>4)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>The OS calls the DllMain of each<br />
loaded DLL, giving it a DLL_PROCESS_DETACH notification.<span style="mso-spacerun: yes">&nbsp; </span>The ‘lpReserved’ argument to DllMain<br />
indicates whether the DLL is being unloaded from a running process or whether<br />
the DLL is being unloaded as part of a process shutdown.<span style="mso-spacerun: yes">&nbsp; </span>(In the case of the CLR’s DllMain, we<br />
only ever receive the latter style of notification.<span style="mso-spacerun: yes">&nbsp; </span>Once we’re loaded into a process, we<br />
won’t be unloaded until the process goes away).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l0 level1 lfo1; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>5)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>The process actually terminates,<br />
and the OS reclaims all the resources associated with the process.</font></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Help Desk Software">Help Desk Software</a>: for your business. Java Custom Software Soulutions and Service.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/a-web-site-is-not-an-rss-feednor-the-reverse/"  title="A web site is not an RSS feed...nor the reverse.">A web site is not an RSS feed&#8230;nor the reverse.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/merry-christmas-indeed/"  title="Merry Christmas Indeed!">Merry Christmas Indeed!</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/silverlight-2-beta-1-cross-domain-bug/"  title="Silverlight 2 Beta 1 Cross Domain Bug">Silverlight 2 Beta 1 Cross Domain Bug</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/link-love-09212007/"  title="Link Love: 09/21/2007">Link Love: 09/21/2007</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/compatability/"  title="Compatability">Compatability</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/be-my-support-group/"  title="Be my Support Group">Be my Support Group</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Well,<br />
that sounds orderly enough.<span style="mso-spacerun: yes">&nbsp; </span>But try<br />
running a multi-threaded process that calls ExitProcess from one thread and<br />
calling HeapAlloc / HeapFree in a loop from a second thread.<span style="mso-spacerun: yes">&nbsp; </span>If you have a debugger attached,<br />
eventually you will trap with an ‘INT 3’ instruction in the OS heap code.<span style="mso-spacerun: yes">&nbsp; </span>The OutputDebugString message will<br />
indicate that a block has been freed, but has not been added to the free list…<br />
It has been leaked.<span style="mso-spacerun: yes">&nbsp; </span>That’s because<br />
the ExitProcess wacked your 2<sup>nd</sup> thread while it was in the middle of<br />
a HeapFree operation.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
symptomatic of a larger problem.<span style="mso-spacerun: yes">&nbsp; </span>If<br />
you wack threads while they are performing arbitrary processing, your<br />
application will be left in an arbitrary state.<span style="mso-spacerun: yes">&nbsp; </span>When the DLL_PROCESS_DETACH<br />
notifications reach your DllMain, you must tolerate that arbitrary<br />
state.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Softwre Development">Softwre Development</a> for small and middle size companies. World-class software applications.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/note-to-self-blog-about-using-service-broker/"  title="Note to self: Blog about using Service Broker">Note to self: Blog about using Service Broker</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfile-vs-loadfrom/"  title="LoadFile vs. LoadFrom">LoadFile vs. LoadFrom</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfroms-second-bind/"  title="LoadFrom's Second Bind">LoadFrom&#8217;s Second Bind</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/merry-christmas-indeed/"  title="Merry Christmas Indeed!">Merry Christmas Indeed!</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/doing-the-deal-and-dishing-the-dirt/"  title="Doing the Deal and Dishing the Dirt">Doing the Deal and Dishing the Dirt</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/c-30-lambdas-and-type-inference/"  title="C# 3.0 Lambdas and Type Inference">C# 3.0 Lambdas and Type Inference</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/access-to-old-blogs/"  title="Access to old blogs">Access to old blogs</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/compatability/"  title="Compatability">Compatability</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’ve<br />
been told by several OS developers that it is the application’s responsibility<br />
to take control of all the threads before calling ExitProcess.<span style="mso-spacerun: yes">&nbsp; </span>That way, the application will be in a<br />
consistent state when DLL_PROCESS_DETACH notifications occur. If you work in the<br />
operating system, it’s reasonable to consider the “application” to be a<br />
monolithic homogenous piece of code written by a single author.<span style="mso-spacerun: yes">&nbsp; </span>So of course that author should put his<br />
house in order and know what all the threads are doing before calling<br />
ExitProcess.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But if<br />
you work on an application, you know that there are always multiple components<br />
written by multiple authors from different vendors.<span style="mso-spacerun: yes">&nbsp; </span>These components are only loosely aware<br />
of each other’s implementations – which is how it should be.<span style="mso-spacerun: yes">&nbsp; </span>And some of these components have extra<br />
threads on the side, or they are performing background processing via<br />
IOCompletion ports, threadpools, or other techniques.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Under<br />
those conditions, nobody can have the global knowledge and global control<br />
necessary to call ExitProcess “safely”.<span style="mso-spacerun: yes">&nbsp;<br />
</span>So, regardless of the official rules, ExitProcess will be called while<br />
various threads are performing arbitrary processing.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>The OS<br />
Loader Lock<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>It’s<br />
impossible to discuss the Win32 model for shutting down a process without<br />
considering the OS loader lock.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This is a lock that is present on all Windows operating systems.<span style="mso-spacerun: yes">&nbsp; </span>It provides mutual exclusion during<br />
loading and unloading.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Unfortunately, this lock is held while application code executes.<span style="mso-spacerun: yes">&nbsp; </span>This fact alone is sufficient to<br />
guarantee disaster.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you<br />
can avoid it, you must never hold one of your own locks while calling into<br />
someone else’s code.<span style="mso-spacerun: yes">&nbsp; </span>They will<br />
screw you every time.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Like all<br />
good rules, this one is made to be broken.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The CLR violates this rule in a few places.<span style="mso-spacerun: yes">&nbsp; </span>For example, we hold a ‘class<br />
constructor’ lock for your class when we call your.cctor method.<span style="mso-spacerun: yes">&nbsp; </span>However, the CLR recognizes that this<br />
fact can lead to deadlocks and other problems.<span style="mso-spacerun: yes">&nbsp; </span>So we have rules for weakening this lock<br />
when we discover cycles of.cctor locks in the application, even if these cycles<br />
are distributed over multiple threads in multi-threaded scenarios.<span style="mso-spacerun: yes">&nbsp; </span>And we can see through various other<br />
locks, like the locks that coordinate JITting, so that larger cycles can be<br />
detected.<span style="mso-spacerun: yes">&nbsp; </span>However, we deliberately<br />
don’t look through user locks (though we could see through many of these, like<br />
Monitors, if we chose).<span style="mso-spacerun: yes">&nbsp; </span>Once we<br />
discover a visible, breakable lock, we allow one thread in the cycle to see<br />
uninitialized state of one of the classes.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This allows forward progress and the application continues.<span style="mso-spacerun: yes">&nbsp; </span>See my earlier blog on “Initializing<br />
code” for more details.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Incidentally, I find it disturbing that there’s often little discipline<br />
in how managed locks like Monitors are used.<span style="mso-spacerun: yes">&nbsp; </span>These locks are so convenient,<br />
particularly when exposed with language constructs like C# lock and VB.NET<br />
SyncLock (which handle backing out of the lock during exceptions), that many<br />
developers ignore good hygiene when using them.<span style="mso-spacerun: yes">&nbsp; </span>For example, if code uses multiple locks<br />
then these locks should typically be ranked so that they are always acquired in<br />
a predictable order.<span style="mso-spacerun: yes">&nbsp; </span>This is one<br />
common technique for avoiding deadlocks.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway,<br />
back to the loader lock.<span style="mso-spacerun: yes">&nbsp; </span> The<br />
OS takes this lock implicitly when it is executing inside APIs like<br />
GetProcAddress, GetModuleHandle and GetModuleFileName.<span style="mso-spacerun: yes">&nbsp; </span>By holding this lock inside these APIs,<br />
the OS ensures that DLLs are not loading and unloading while it is groveling<br />
through whatever tables it uses to record the state of the process.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So if<br />
you call those APIs, you are implicitly acquiring a lock.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>That<br />
same lock is also acquired during a LoadLibrary, FreeLibrary, or CreateThread<br />
call.<span style="mso-spacerun: yes">&nbsp; </span>And – while it is held – the<br />
operating system will call your DllMain routine with a notification.<span style="mso-spacerun: yes">&nbsp; </span>The notifications you might see<br />
are:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><i style="mso-bidi-font-style: normal"><font size=2></font><font face=Tahoma>DLL_THREAD_ATTACH<o :p></o></font></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
thread that calls your DllMain has just been injected into the process.<span style="mso-spacerun: yes">&nbsp; </span>If you need to eagerly allocate any TLS<br />
state, this is your opportunity to do so.<span style="mso-spacerun: yes">&nbsp;<br />
</span>In the managed world, it is preferable to allocate TLS state lazily on<br />
the first TLS access on a given thread.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><i style="mso-bidi-font-style: normal"><font size=2></font><font face=Tahoma>DLL_THREAD_DETACH<o :p></o></font></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
thread that calls your DllMain has finished executing the thread procedure that<br />
it was started up with.<span style="mso-spacerun: yes">&nbsp; </span>After it<br />
finishes notifying all the DLLs of its death in this manner, it will<br />
terminate.<span style="mso-spacerun: yes">&nbsp; </span>Many unmanaged<br />
applications use this notification to de-allocate their TLS data.<span style="mso-spacerun: yes">&nbsp; </span>In the managed world, managed TLS is<br />
automatically cleaned up without your intervention.<span style="mso-spacerun: yes">&nbsp; </span>This happens as a natural consequence of<br />
garbage collection.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><i style="mso-bidi-font-style: normal"><font size=2></font><font face=Tahoma>DLL_PROCESS_ATTACH<o :p></o></font></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
thread that calls your DllMain is loading your DLL via an explicit LoadLibraryEx<br />
call or similar technique, like a static bind.<span style="mso-spacerun: yes">&nbsp; </span>The lpReserved argument indicates<br />
whether a dynamic or static bind is in progress.<span style="mso-spacerun: yes">&nbsp; </span>This is your opportunity to initialize<br />
any global state that could not be burned into the image.<span style="mso-spacerun: yes">&nbsp; </span>For example, C++ static initializers<br />
execute at this time.<span style="mso-spacerun: yes">&nbsp; </span>The managed<br />
equivalent has traditionally been a class constructor method, which executes<br />
once per AppDomain.<span style="mso-spacerun: yes">&nbsp; </span>In a future<br />
version of the CLR, we hope to provde a more convenient module constructor<br />
concept.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><i style="mso-bidi-font-style: normal"><font size=2></font><font face=Tahoma>DLL_PROCESS_DETACH<o :p></o></font></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If the<br />
process is terminating in an orderly fashion (ExitProcess), your DllMain will<br />
receive a DLL_PROCESS_DETACH notification where the lpReserved argument is<br />
non-null.<span style="mso-spacerun: yes">&nbsp; </span>If the process is<br />
terminating in a rude fashion (TerminateProcess), your DllMain will receive no<br />
notification.<span style="mso-spacerun: yes">&nbsp; </span>If someone unloads<br />
your DLL via a call to FreeLibrary or equivalent, the process will continue<br />
executing after you unload.<span style="mso-spacerun: yes">&nbsp; </span>This case is indicated by a null value for<br />
lpReserved.<span style="mso-spacerun: yes">&nbsp; </span>In the managed world, de-initialization<br />
happens through notifications of AppDomain unload or process exit, or through<br />
finalization activity.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The DLL_THREAD_ATTACH and<br />
DLL_THREAD_DETACH calls have a performance implication.<span style="mso-spacerun: yes">&nbsp; </span>If you have loaded<br />
100 DLLs into your process and you start a new thread, that thread must call 100<br />
different DllMain routines.<span style="mso-spacerun: yes">&nbsp; </span>Let’s say that these routines touch a page or<br />
two of code each, and a page of data.<span style="mso-spacerun: yes">&nbsp; </span>That might be 250 pages (1 MB) in your<br />
working set, for no good reason.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The CLR calls DisableThreadLibraryCalls<br />
on all managed assemblies other than certain MC++ IJW assemblies (more on this<br />
later) to avoid this overhead for you.<span style="mso-spacerun: yes">&nbsp; </span>And it’s a good idea to do the same on your<br />
unmanaged DLLs if they don’t need these notifications to manage their<br />
TLS.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Writing code inside DllMain is one of<br />
the most dangerous places to write code.<span style="mso-spacerun: yes">&nbsp; </span>This is because you are executing inside a<br />
callback from the OS loader, inside the OS loader lock.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Here are some of the rules related to<br />
code inside DllMain:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l10 level1 lfo2; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>You must never call LoadLibrary or<br />
otherwise perform a dynamic bind.</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l10 level1 lfo2; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>You must never attempt to acquire a<br />
lock, if that lock might be held by a thread that needs the OS loader lock.<span style="mso-spacerun: yes">&nbsp; </span>(Acquiring a heap<br />
lock by calling HeapAlloc or HeapFree is probably okay).</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l10 level1 lfo2; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>3)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>You should never call into another<br />
DLL.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
danger is that the other DLL may not have initialized yet, or it may have<br />
already uninitialized.<span style="mso-spacerun: yes">&nbsp; </span>(Calling into kernel32.dll is probably<br />
okay).</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l10 level1 lfo2; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>4)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>You should never start up a thread or<br />
terminate a thread, and then rendezvous with that other thread’s start or<br />
termination.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>As we shall see, the CLR violates some<br />
of these rules.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And these violations have resulted in serious consequences for managed<br />
applications – particularly managed applications written in MC++.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>And if you’ve ever written code inside<br />
DllMain – including code that’s implicitly inside DllMain like C++ static<br />
initializers or ‘atexit’ routines – then you’ve probably violated some of these<br />
rules.<span style="mso-spacerun: yes">&nbsp; </span>Rule #3<br />
is especially harsh.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The fact is, programs violate these<br />
rules all the time and get away with it.<span style="mso-spacerun: yes">&nbsp; </span>Knowing this, the MC++ and CLR teams made a<br />
bet that they could violate some of these rules when executing IJW<br />
assemblies.<span style="mso-spacerun: yes">&nbsp; </span>It<br />
turns out that we bet wrong.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’m going to explain exactly how we<br />
screwed this up with IJW assemblies, but first I need to explain what IJW<br />
assemblies are.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>IJW<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>IJW is how we internally refer to mixed<br />
managed / unmanaged images.<span style="mso-spacerun: yes">&nbsp; </span>If you compile a MC++ assembly with ‘/clr’ in<br />
V1 or V1.1, it almost certainly contains a mixture of managed and unmanaged<br />
constructs.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In future versions, I expect there will<br />
be ways to compile MC++ assemblies with compiler-enforced guarantees that the<br />
image is guaranteed pure managed, or guaranteed pure verifiable managed, or –<br />
ultimately – perhaps even pure verifiable 32-bit / 64-bit neutral managed.<span style="mso-spacerun: yes">&nbsp; </span>In each case, the<br />
compiler will necessarily have to restrict you to smaller and smaller subsets of<br />
the C++ language.<span style="mso-spacerun: yes">&nbsp;<br />
</span>For example, verifiable C++ cannot use arbitrary unmanaged pointers.<span style="mso-spacerun: yes">&nbsp; </span>Instead, it must<br />
restrict itself to managed pointers and references, which are reported to the<br />
garbage collector and which follow certain strict rules.<span style="mso-spacerun: yes">&nbsp; </span>Furthermore, 32-bit<br />
/ 64-bit neutral code cannot consume the declarations strewn through the<br />
windows.h headers, because these pick a word size during compilation.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>IJW is an acronym for “It Just Works”<br />
and it reflects the shared goal of the C++ and CLR teams to transparently<br />
compile existing arbitrary C++ programs into IL.<span style="mso-spacerun: yes">&nbsp; </span>I think we did an amazing job of approaching<br />
that goal, but of course not everything “just works.”<span style="mso-spacerun: yes">&nbsp; </span>First, there are a<br />
number of constructs like inline assembly language that cannot be converted to<br />
managed execution.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The C++ compiler, linker and CLR ensure that these methods are left as<br />
unmanaged and that managed callers transparently switch back to unmanaged before<br />
calling them.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So inline X86 assembly language must<br />
necessarily remain in unmanaged code.<span style="mso-spacerun: yes">&nbsp; </span>Some other constructs are currently left in<br />
unmanaged code, though with sufficient effort we could provide managed<br />
equivalents.<span style="mso-spacerun: yes">&nbsp;<br />
</span>These other constructs include setjmp / longjmp, member pointers (like<br />
pointer to virtual method), and a reasonable startup / shutdown story (which is<br />
what this blog article is <i style="mso-bidi-font-style: normal">supposed</i> to be about).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’m not sure if we ever documented the<br />
constructs that are legal in a pure managed assembly, vs. those constructs which<br />
indicate that the assembly is IJW.<span style="mso-spacerun: yes">&nbsp; </span>Certainly we have a strict definition of this<br />
distinction embedded in our code, because the managed loader considers it when<br />
loading.<span style="mso-spacerun: yes">&nbsp; </span>Some<br />
of the things we consider are:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo3; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>A pure<br />
 managed assembly has exactly one DLL import.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>This import is to mscoree.dll’s _CorExeMain<br />
 (for an EXE) or _CorDllMain (for a DLL).<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>The entrypoint of the EXE or DLL must be a<br />
 JMP to this import.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>This is how we force the runtime to load and get control whenever a<br />
 managed assembly is loaded.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="mso-spacerun: yes"><font face=Tahoma size=2></font></span>&nbsp;</p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo3; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>A pure<br />
 managed assembly can have no DLL exports.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>When we bind to pure managed assemblies, it<br />
 is always through managed Fusion services, via AssemblyRefs and assembly<br />
 identities (ideally with cryptographic strong names).</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo3; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>A pure<br />
 managed assembly has exactly one rebasing fixup.<span style="mso-spacerun: yes">&nbsp; </span>This fixup is for<br />
 the JMP through the import table that I mentioned above.<span style="mso-spacerun: yes">&nbsp; </span>Unmanaged EXEs<br />
 tend to strip all their rebasing fixups, since EXEs are almost guaranteed to<br />
 load at their preferred addresses.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>However, managed EXEs can be loaded like<br />
 DLLs into a running process.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>That single fixup is useful for cases where<br />
 we want to load via LoadLibraryEx on versions of the operating system that<br />
 support this.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo3; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>A pure<br />
 managed assembly has no TLS section and no other exotic constructs that are<br />
 legal in arbitrary unmanaged PE files.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of course, IJW assemblies can have many<br />
imports, exports, fixups, and other constructs.<span style="mso-spacerun: yes">&nbsp; </span>As with pure managed assemblies, the<br />
entrypoint is constrained to be a JMP to mscoree.dll’s _CorExeMain or<br />
_CorDllMain function.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This is the “outer entrypoint”.<span style="mso-spacerun: yes">&nbsp; </span>However, the COM+ header of the PE file has<br />
an optional “inner entrypoint”.<span style="mso-spacerun: yes">&nbsp; </span>Once the CLR has proceeded far enough into<br />
the loading process on a DLL, it will dispatch to this inner entrypoint which<br />
is… your normal DllMain.<span style="mso-spacerun: yes">&nbsp; </span>In V1 and V1.1, this inner entrypoint is<br />
expressed as a token to a managed function.<span style="mso-spacerun: yes">&nbsp; </span>Even if your DllMain is written as an<br />
unmanaged function, we dispatch to a managed function which is defined as a<br />
PInvoke out to the unmanaged function.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Now we can look at the set of rules for<br />
what you can do in a DllMain, and compare it to what the CLR does when it sees<br />
an IJW assembly.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The results aren’t pretty.<span style="mso-spacerun: yes">&nbsp; </span>Remember that inside DllMain:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><i style="mso-bidi-font-style: normal"><u><font size=2></font><font face=Tahoma>You must never call LoadLibrary or otherwise perform a<br />
dynamic bind<o :p></o></font></u></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>With normal managed assemblies, this<br />
isn’t a concern.<span style="mso-spacerun: yes">&nbsp;<br />
</span>For example, most pure managed assemblies are loaded through<br />
Assembly.Load or resolution of an AssemblyRef – outside of the OS loader<br />
lock.<span style="mso-spacerun: yes">&nbsp; </span>Even<br />
activation of a managed COM object through OLE32’s CoCreateInstance will<br />
sidestep this issue.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The registry entries for the CLSID always mention mscoree.dll as the<br />
server.<span style="mso-spacerun: yes">&nbsp; </span>A<br />
subkey is consulted by mscoree.dll – inside DllGetClassObject and outside of the<br />
OS loader lock – to determine which version of the runtime to spin up and which<br />
assembly to load.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But IJW assemblies have arbitrary DLL<br />
exports.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Therefore other DLLs, whether unmanaged or themselves IJW, can have<br />
static or dynamic (GetProcAddress) dependencies on an IJW assembly.<span style="mso-spacerun: yes">&nbsp; </span>When the OS loads<br />
the IJW assembly inside the loader lock, the OS further resolves the static<br />
dependency from the IJW assembly to mscoree.dll’s _CorDllMain.<span style="mso-spacerun: yes">&nbsp; </span>Inside _CorDllMain,<br />
we must select an appropriate version of the CLR to initialize in the<br />
process.<span style="mso-spacerun: yes">&nbsp; </span>This<br />
involves calling LoadLibrary on a particular version of mscorwks.dll, violating<br />
our first rule for DllMain.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So what goes wrong when this rule is<br />
violated?<span style="mso-spacerun: yes">&nbsp;<br />
</span>Well, the OS loader has already processed all the DLLs and their imports,<br />
walking the tree of static dependencies and forming a loading plan.<span style="mso-spacerun: yes">&nbsp; </span>It is now executing<br />
on this plan.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Let’s say that the loader’s plan is to first initialize an IJW assembly,<br />
then initialize its dependent mscoree.dll reference, and then initialize<br />
advapi32.dll.<span style="mso-spacerun: yes">&nbsp;<br />
</span>(By ‘initialize’, I mean give that DLL its DLL_PROCESS_ATTACH<br />
notification).<span style="mso-spacerun: yes">&nbsp;<br />
</span>When mscoree.dll decides to LoadLibrary mscorwks.dll, a new loader plan<br />
must be created.<span style="mso-spacerun: yes">&nbsp;<br />
</span>If mscorwks.dll depends on advapi32.dll (and of course it does), we have<br />
a problem.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
OS loader already has advapi32.dll on its pending list.<span style="mso-spacerun: yes">&nbsp; </span>It will initialize<br />
that DLL when it gets far enough into its original loading plan, but not<br />
before.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If mscorwks.dll needs to call some APIs<br />
inside advapi32.dll, it will now be making those calls before advapi32.dll’s<br />
DllMain has been called.<span style="mso-spacerun: yes">&nbsp; </span>This can and does lead to arbitrary<br />
failures.<span style="mso-spacerun: yes">&nbsp; </span>I<br />
personally hear about problems with this every 6 months or so.<span style="mso-spacerun: yes">&nbsp; </span>That’s a pretty low<br />
rate of failure.<span style="mso-spacerun: yes">&nbsp;<br />
</span>But one of those failures was triggered when a healthy application<br />
running on V1 of the CLR was moved to V1.1 of the CLR.<span style="mso-spacerun: yes">&nbsp; </span>Ouch.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><i style="mso-bidi-font-style: normal"><u><font size=2></font><font face=Tahoma>You must never attempt to acquire a lock, if that lock<br />
might be held by a thread that needs the OS loader lock<o :p></o></font></u></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>It’s not possible to execute managed<br />
code without potentially acquiring locks on your thread.<span style="mso-spacerun: yes">&nbsp; </span>For example, we may<br />
need to initialize a class that you need access to.<span style="mso-spacerun: yes">&nbsp; </span>If that class isn’t<br />
already initialized in your AppDomain, we will use a.cctor lock to coordinate<br />
initialization.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Along the same lines, if a method requires JIT compilation we will use a<br />
lock to coordinate this.<span style="mso-spacerun: yes">&nbsp; </span>And if your thread allocates a managed<br />
object, it may have to take a lock.<span style="mso-spacerun: yes">&nbsp; </span>(We don’t take a lock on each allocation if<br />
we are executing on a multi-processor machine, for obvious reasons.<span style="mso-spacerun: yes">&nbsp; </span>But eventually your<br />
thread must coordinate with the garbage collector via a lock before it can<br />
proceed with more allocations).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So if you execute managed code inside<br />
the OS loader lock, you are going to contend for a CLR lock.<span style="mso-spacerun: yes">&nbsp; </span>Now consider what<br />
happens if the CLR ever calls GetModuleHandle or GetProcAddress or<br />
GetModuleFileName while it holds one of those other locks.<span style="mso-spacerun: yes">&nbsp; </span>This includes<br />
implicit calls to LoadLibrary / GetProcAddress as we fault in any lazy DLL<br />
imports from the CLR.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Unfortunately, the sequence of lock<br />
acquisition is inverted on the two threads.<span style="mso-spacerun: yes">&nbsp; </span>This yields a classic deadlock.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Once again, this isn’t a concern for<br />
pure managed assemblies.<span style="mso-spacerun: yes">&nbsp; </span>The only way a pure managed assembly can<br />
execute managed code inside the OS loader lock is if some unmanaged code<br />
explicitly calls into it via a marshaled out delegate or via a COM call from <i style="mso-bidi-font-style: normal">its own</i><br />
DllMain.<span style="mso-spacerun: yes">&nbsp;<br />
</span>That’s a bug in the unmanaged code!<span style="mso-spacerun: yes">&nbsp; </span>But with an IJW assembly, some methods are<br />
managed and some are unmanaged.<span style="mso-spacerun: yes">&nbsp; </span>The compiler, linker and CLR conspire to make<br />
this fact as transparent as possible.<span style="mso-spacerun: yes">&nbsp; </span>But any call from your DllMain (i.e. from<br />
your inner entrypoint) to a method that happened to be emitted as IL will set<br />
you up for this deadlock.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><i style="mso-bidi-font-style: normal"><u><font face=Tahoma size=2>You should<br />
never call into another DLL</font></u></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>It’s really not possible to execute<br />
managed code without making cross-DLL calls.<span style="mso-spacerun: yes">&nbsp; </span>The JIT compiler is in a different DLL from<br />
the ExecutionEngine.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The ExecutionEngine is in a different DLL from your IJW<br />
assembly.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Once again, pure managed assemblies<br />
don’t usually have a problem here.<span style="mso-spacerun: yes">&nbsp; </span>I did run into one case where one of the<br />
Microsoft language compilers was doing a LoadLibrary of mscorlib.dll.<span style="mso-spacerun: yes">&nbsp; </span>This had the side<br />
effect of spinning up the CLR inside the OS loader lock and inflicting all the<br />
usual IJW problems onto the compilation process.<span style="mso-spacerun: yes">&nbsp; </span>Since managed assemblies have no DLL exports,<br />
it’s rare for applications to load them in this manner.<span style="mso-spacerun: yes">&nbsp; </span>In the case of this<br />
language compiler, it was doing so for the obscure purpose of printing a banner<br />
to the console at the start of compilation, telling the user what version of the<br />
CLR it was bound to.<span style="mso-spacerun: yes">&nbsp;<br />
</span>There are much better ways of doing this sort of thing, and none of those<br />
other ways would interfere with the loader lock.<span style="mso-spacerun: yes">&nbsp; </span>This has been corrected.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="mso-spacerun: yes"><font face=Tahoma size=2></font></span>&nbsp;</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font size=2></font><font face=Tahoma><i style="mso-bidi-font-style: normal"><u>You should never start up a thread or terminate a thread,<br />
and then rendezvous</u></i> </font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This probably doesn’t sound like<br />
something you would do.<span style="mso-spacerun: yes">&nbsp; </span>And yet it’s one of the most common deadlocks<br />
I see with IJW assemblies on V1 and V1.1 of the CLR.<span style="mso-spacerun: yes">&nbsp; </span>The typical stack<br />
trace contains a load of an IJW assembly, usually via a DLL import.<span style="mso-spacerun: yes">&nbsp; </span>This causes<br />
mscoree.dll’s _CorDllMain to get control.<span style="mso-spacerun: yes">&nbsp; </span>Eventually, we notice that the IJW assembly<br />
has been strong name signed, so we call into WinVerifyTrust in<br />
WinTrust.dll.<span style="mso-spacerun: yes">&nbsp;<br />
</span>That API has a perfectly reasonable expectation that it is not inside the<br />
OS loader lock.<span style="mso-spacerun: yes">&nbsp;<br />
</span>It calls into the OS threadpool (not the managed CLR threadpool), which<br />
causes the OS threadpool to lazily initialize itself.<span style="mso-spacerun: yes">&nbsp; </span>Lazy initialization<br />
involves spinning up a waiter thread, and then blocking until that waiter thread<br />
starts executing.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of course, the new waiter thread must<br />
first deliver DLL_THREAD_ATTACH notifications to any DLLs that expect such<br />
notifications.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And it must obviously obtain the OS loader lock before it can deliver the<br />
first notification.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The result is a deadlock.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So I’ve painted a pretty bleak picture<br />
of all the things that can go wrong with IJW assemblies in V1 and V1.1 of the<br />
CLR.<span style="mso-spacerun: yes">&nbsp; </span>If we had<br />
seen a disturbing rate of failures prior to shipping V1, we would have<br />
reconsidered our position here.<span style="mso-spacerun: yes">&nbsp; </span>But it wasn’t until later that we had enough<br />
external customers running into these difficulties.<span style="mso-spacerun: yes">&nbsp; </span>With the benefits<br />
of perfect hindsight, it is now clear that we screwed up.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Fortunately, much of this is fixable in<br />
our next release.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Until then, there are some painful workarounds that might bring you some<br />
relief.<span style="mso-spacerun: yes">&nbsp; </span>Let’s<br />
look at the ultimate solution first, and then you can see how the workarounds<br />
compare.<span style="mso-spacerun: yes">&nbsp; </span>We<br />
think that the ultimate solution would consist of several parts:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l6 level1 lfo6; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Just<br />
 loading an IJW assembly must not spin up a version of the CLR.<span style="mso-spacerun: yes">&nbsp; </span>That’s because<br />
 spinning up a version of the CLR necessarily involves a dynamic load, and<br />
 we’ve seen that dynamic loads are illegal during loading and initializing of<br />
 static DLL dependencies.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Instead, mscoree.dll must perform enough<br />
 initialization of the IJW assembly without actually setting up a full<br />
 runtime.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>This means that all calls into the managed portion of the IJW assembly<br />
 must be bashed so that they lazily load a CLR and initialize it on first<br />
 call.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=2>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l6 level1 lfo6; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Along the<br />
 same lines, the inner entrypoint of an IJW assembly must either be omitted or<br />
 must be encoded as an unmanaged entrypoint.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Recall that the current file format doesn’t<br />
 have a way of representing unmanaged inner entrypoints, since this is always<br />
 in the form of a token.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Even if the token refers to an unmanaged<br />
 method, we would have to spin up a version of the CLR to interpret that token<br />
 for us.<span style="mso-spacerun: yes">&nbsp; </span>So<br />
 we’re going to need a tweak to the current file format to enable unmanaged<br />
 inner entrypoints.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=3>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l6 level1 lfo6; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>An<br />
 unmanaged inner entrypoint is still a major risk.<span style="mso-spacerun: yes">&nbsp; </span>If that inner<br />
 entrypoint calls into managed code, we will trap the call and lazily spin up<br />
 the correction version of the CLR.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>At that point, you are in exactly the same<br />
 situation as if we had left the entrypoint as managed.<span style="mso-spacerun: yes">&nbsp; </span>Ideally,<br />
 assembly-level initialization and uninitialization would never happen inside<br />
 the OS loader lock.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Instead, they would be replaced with modern managed analogs that are<br />
 unrelated to the unmanaged OS loader’s legacy behavior.<span style="mso-spacerun: yes">&nbsp; </span>If you read my<br />
 old blog on “Initializing code” at </font>http://blogs.gotdotnet.com/cbrumme/PermaLink.aspx/611cdfb1-2865-4957-9a9c-6e2655879323 <font face=Tahoma size=2>, I mention that we’re under some<br />
 pressure to add a module-level equivalent of.cctor methods.<span style="mso-spacerun: yes">&nbsp; </span>That mechanism<br />
 would make a great replacement for traditional DLL_PROCESS_ATTACH<br />
 notifications.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>In fact, the CLR has always supported a.cctor method at a global<br />
 module scope.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>However, the semantics associated with such a method was that it ran<br />
 before any access to static members at global module scope.<span style="mso-spacerun: yes">&nbsp; </span>A more useful<br />
 semantic for a future version of the CLR would be for such a global.cctor to<br />
 execute before any access to members in the containing Module, whether global<br />
 or contained in any of the Module’s types.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=4>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l6 level1 lfo6; tab-stops: list.5in"<br />
 ><font size=2></font><font face=Tahoma<br />
 >The above changes make it possible to avoid execution of<br />
 managed code inside the OS loader lock.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>But it’s still possible for a naïve or<br />
 misbehaved unmanaged application to call a managed service (like a marshaled<br />
 out delegate or a managed COM object) from inside DllMain.<span style="mso-spacerun: yes">&nbsp; </span>This final<br />
 scenario is not specific to IJW.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>All managed execution is at risk to this<br />
 kind of abuse.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Ideally, the CLR would be able to detect attempts to enter it while the<br />
 loader lock is held, and fail these attempts.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>It’s not clear whether such detection /<br />
 prevention should be unconditional or whether it should be enabled through a<br />
 Customer Debug Probe.<i style="mso-bidi-font-style: normal"<br />
 ><o :p></o></i></font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><i style="mso-bidi-font-style: normal"><font face=Tahoma<br />
size=2>If you don’t know what Customer Debug Probes are,<br />
please hunt them down on MSDN.<span style="mso-spacerun: yes">&nbsp; </span>They are a life-saver for debugging certain<br />
difficult problems in managed applications.<span style="mso-spacerun: yes">&nbsp; </span>I would recommend starting with </font>http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=c7b955c7-231a-406c-9fa5-ad09ef3bb37f <font face=Tahoma size=2>, and then reading most of Adam Nathan’s<br />
excellent blogs at </font>http://blogs.gotdotnet.com/anathan <font size=2></font><font face=Tahoma>.<o :p></o></font></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><i style="mso-bidi-font-style: normal"><o :p><font face=Tahoma size=2></font></o></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of the above 4 changes, we’re relatively<br />
confident that the first 3 will happen in the next release.<span style="mso-spacerun: yes">&nbsp; </span>We also<br />
experimented with the 4<sup>th</sup> change, but it’s<br />
unlikely that we will make much further progress.<span style="mso-spacerun: yes">&nbsp; </span>A key obstacle is that there is no<br />
OS-approved way that can efficiently detect execution inside the loader<br />
lock.<span style="mso-spacerun: yes">&nbsp; </span>Our hope<br />
is that a future version of the OS would provide such a mechanism.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is all great.<span style="mso-spacerun: yes">&nbsp; </span>But you have an<br />
application that must run on V1 or V1.1.<span style="mso-spacerun: yes">&nbsp; </span>What options do you have?<span style="mso-spacerun: yes">&nbsp; </span>Fortunately, Scott<br />
Currie has written an excellent article on this very subject.<span style="mso-spacerun: yes">&nbsp; </span>If you build IJW<br />
assemblies, please read it at </font>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vcconmixeddllloadingproblem.asp <font face=Tahoma size=2>.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>The Pure Managed<br />
Story<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you code in a language other than<br />
MC++, you’re saying “Enough about IJW and the OS loader lock<br />
already.”</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Let’s look at what the CLR does during<br />
process shutdown.<span style="mso-spacerun: yes">&nbsp;<br />
</span>I’ll try not to mention IJW, but I’ll have to keep talking about that<br />
darn loader lock.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>From the point of view of a managed<br />
application, there are three types of shutdown:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l5 level1 lfo7; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>A shutdown initiated by a call to<br />
TerminateProcess doesn’t involve any further execution of the CLR or managed<br />
code.<span style="mso-spacerun: yes">&nbsp; </span>From our<br />
perspective, the process simply disappears.<span style="mso-spacerun: yes">&nbsp; </span>This is the rudest of all shutdowns, and<br />
neither the CLR developer nor the managed developer has any obligations related<br />
to it.</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l5 level1 lfo7; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>A shutdown initiated by a direct call to<br />
ExitProcess is an unorderly shutdown from the point of view of the managed<br />
application.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Our first notification of the shutdown is via a DLL_PROCESS_DETACH<br />
notification.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This notification could first be delivered to the DllMain of<br />
mscorwks.dll, mscoree.dll, or any of the managed assemblies that are currently<br />
loaded.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Regardless of which module gets the notification first, it is always<br />
delivered inside the OS loader lock.<span style="mso-spacerun: yes">&nbsp; </span>It is not safe to execute any managed code at<br />
this time.<span style="mso-spacerun: yes">&nbsp; </span>So<br />
the CLR performs a few house-keeping activities and then returns from its<br />
DllMain as quickly as possible.<span style="mso-spacerun: yes">&nbsp; </span>Since no managed code runs, the managed<br />
developer still has no obligations for this type of shutdown.</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l5 level1 lfo7; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>3)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>An orderly managed shutdown gives<br />
managed code an opportunity to execute outside of the OS loader lock, prior to<br />
calling ExitProcess.<span style="mso-spacerun: yes">&nbsp;<br />
</span>There are several ways we can encounter an orderly shutdown.<span style="mso-spacerun: yes">&nbsp; </span>Because we will<br />
execute managed code, including Finalize methods, the managed developer must<br />
consider this case.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Examples of an orderly managed shutdown<br />
include:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l9 level1 lfo8; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>Call System.Environment.Exit().<span style="mso-spacerun: yes">&nbsp; </span>I already mentioned<br />
that some Windows developers have noted that you must not call ExitProcess<br />
unless you first coordinate all your threads… and then they work like mad to<br />
make the uncoordinated case work.<span style="mso-spacerun: yes">&nbsp; </span>For Environment.Exit we are under no<br />
illusions.<span style="mso-spacerun: yes">&nbsp; </span>We<br />
expect you to call it in races from multiple threads at arbitrary times.<span style="mso-spacerun: yes">&nbsp; </span>It’s our job to<br />
somehow make this work.</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l9 level1 lfo8; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>If a process is launched with a managed<br />
EXE, then the CLR tracks the number of foreground vs. background managed<br />
threads.<span style="mso-spacerun: yes">&nbsp; </span>(See<br />
Thread.IsBackground).<span style="mso-spacerun: yes">&nbsp;<br />
</span>When the number of foreground threads drops to zero, the CLR performs an<br />
orderly shutdown of the process.<span style="mso-spacerun: yes">&nbsp; </span>Note that the distinction between foreground<br />
and background threads serves exactly this purpose and no other<br />
purpose.</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l9 level1 lfo8; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>3)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>Starting with MSVCRT 7.0, an explicit<br />
call to ‘exit()’ or an implicit call to ‘exit()’ due to a return from ‘main()’<br />
can turn into an orderly managed shutdown.<span style="mso-spacerun: yes">&nbsp; </span>The CRT checks to see if mscorwks.dll or<br />
mscoree.dll is in the process (I forget which).<span style="mso-spacerun: yes">&nbsp; </span>If it is resident, then it calls<br />
CorExitProcess to perform an orderly shutdown.<span style="mso-spacerun: yes">&nbsp; </span>Prior to 7.0, the CRT is of course unaware of<br />
the CLR.</font></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l9 level1 lfo8; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>4)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>Some unmanaged applications are aware of<br />
the CLR’s requirements for an orderly shutdown.<span style="mso-spacerun: yes">&nbsp; </span>An example is devenv.exe, which is the EXE<br />
for Microsoft Visual Studio.<span style="mso-spacerun: yes">&nbsp; </span>Starting with version 7, devenv calls<br />
CoEEShutDownCOM to force all the CLR’s references on COM objects to be<br />
Release()’d.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This at least handles part of the managed shutdown in an orderly<br />
fashion.<span style="mso-spacerun: yes">&nbsp; </span>It’s<br />
been a while since I’ve looked at that code, but I think that ultimately devenv<br />
triggers an orderly managed shutdown through a 2<sup>nd</sup> API.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you are following along with the<br />
Rotor sources, this all leads to an interesting quirk of EEShutDown in<br />
ceemain.cpp.<span style="mso-spacerun: yes">&nbsp;<br />
</span>That method can be called:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l7 level1 lfo9; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>0 times, if<br />
 someone calls TerminateProcess.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l7 level1 lfo9; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>1 time, if<br />
 someone initiates an unorderly shutdown via ExitProcess.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l7 level1 lfo9; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>2 times, if<br />
 we have a single-threaded orderly shutdown.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>In this case, the first call is made<br />
 outside of the OS loader lock.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Later, we call ExitProcess for the 2<sup>nd</sup> half of the shutdown.<span style="mso-spacerun: yes">&nbsp; </span>This causes<br />
 EEShutDown to be called a 2<sup>nd</sup> time.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l7 level1 lfo9; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Even more<br />
 times, if we have a multi-threaded orderly shutdown.<span style="mso-spacerun: yes">&nbsp; </span>Many threads will<br />
 race to call EEShutDown the first time, outside the OS loader lock.<span style="mso-spacerun: yes">&nbsp; </span>This routine<br />
 protects itself by anointing a winner to proceed with the shutdown.<span style="mso-spacerun: yes">&nbsp; </span>Then the eventual<br />
 call to ExitProcess causes the OS to kill all threads except one, which calls<br />
 back to EEShutDown inside the OS loader lock.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of course, our passage through<br />
EEShutDown is quite different when we are outside the OS loader lock, compared<br />
to when we are inside it.<span style="mso-spacerun: yes">&nbsp; </span>When we are outside, we do something like<br />
this:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo10; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>First we<br />
 synchronize at the top of EEShutDown, to handle the case where multiple<br />
 threads race via calls to Environment.Exit or some equivalent<br />
 entrypoint.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo10; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Then we<br />
 finalize all objects that are unreachable.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>This finalization sweep is absolutely<br />
 normal and occurs while the rest of the application is still running.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo10; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Then we<br />
 signal for the finalizer thread to finish its normal activity and participate<br />
 in the shutdown.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>The first thing it does is raise the AppDomain.ProcessExit event.<span style="mso-spacerun: yes">&nbsp; </span>Once we get past<br />
 this point, the system is no longer behaving normally.<span style="mso-spacerun: yes">&nbsp; </span>You could either<br />
 listen to this event, or you could poll System.Environment.HasShutdownStarted<br />
 to discover this fact.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>This can be an important fact to discover<br />
 in your Finalize method, because it’s more difficult to write robust<br />
 finalization code when we have started finalizing <i style="mso-bidi-font-style: normal">reachable</i><br />
 objects.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>It’s no longer possible to depend on WaitHandles like Events, remoting<br />
 infrastructure, or other objects.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>The other time we can finalize reachable<br />
 objects is during an AppDomain unload.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>This case can be discovered by listening to<br />
 the AppDomain.DomainUnload event or by polling for the<br />
 AppDomain.IsFinalizingForUnload state.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>The other nasty thing to keep in mind is<br />
 that you can only successfully listen to the ProcessExit event from the<br />
 Default AppDomain.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>This is something of a bug and I think we would like to try fixing it<br />
 for the next release.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo10; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Before we<br />
 can start finalizing reachable objects, we suspend all managed activity.<span style="mso-spacerun: yes">&nbsp; </span>This is a<br />
 suspension from which we will never resume.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Our goal is to minimize the number of<br />
 threads that are surprised by the finalization of reachable state, like static<br />
 fields, and it’s similar to how we prevent entry to a doomed AppDomain when we<br />
 are unloading it.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo10; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>This<br />
 suspension is unusual in that we allow the finalizer thread to bypass the<br />
 suspension.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Also, we change suspended threads that are in STAs, so that they pump<br />
 COM messages.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>We would never do this during a garbage collection, since the<br />
 reentrancy would be catastrophic.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>(Threads are suspended for a GC at pretty<br />
 arbitrary places… down to an arbitrary machine code instruction boundary in<br />
 many typical scenarios).<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>But since we are never going to resume from<br />
 this suspension, and since we don’t want cross-apartment COM activity to<br />
 deadlock the shutdown attempt, pumping makes sense here.<span style="mso-spacerun: yes">&nbsp; </span>This suspension<br />
 is also unusual in how we raise the barrier against managed execution.<span style="mso-spacerun: yes">&nbsp; </span>For normal GC<br />
 suspensions, threads attempting to call from unmanaged to managed code would<br />
 block until the GC completes.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>In the case of a shutdown, this could cause<br />
 deadlocks when it is combined with cross-thread causality (like synchronous<br />
 cross-apartment calls).<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Therefore the barrier behaves differently<br />
 during shutdown.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Returns into managed code block normally.<span style="mso-spacerun: yes">&nbsp; </span>But calls into<br />
 managed code are failed.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>If the call-in attempt is on an HRESULT<br />
 plan, we return an HRESULT.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>If it is on an exception plan, we<br />
 throw.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
 exception code we raise is 0xC0020001 and the argument to RaiseException is a<br />
 failure HRESULT formed from the ERROR_PROCESS_ABORTED SCODE (0x1067).</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo10; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Once all<br />
 objects have been finalized, even if they are reachable, then we Release() all<br />
 the COM pUnks that we are holding.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Normally, releasing a chain of pUnks from a<br />
 traced environment like the CLR involves multiple garbage collections.<span style="mso-spacerun: yes">&nbsp; </span>Each collection<br />
 discovers a pUnk in the chain and subsequently Release’s it.<span style="mso-spacerun: yes">&nbsp; </span>If that Release<br />
 on the unmanaged side is the final release, then the unmanaged pUnk will be<br />
 free’d.<span style="mso-spacerun: yes">&nbsp; </span>If<br />
 that pUnk contains references to managed objects, those references will now be<br />
 dropped.<span style="mso-spacerun: yes">&nbsp; </span>A<br />
 subsequent GC may now collect this managed object and the cycle begins<br />
 again.<span style="mso-spacerun: yes">&nbsp; </span>So a<br />
 chain of pUnks that interleaves managed and unmanaged execution can require a<br />
 GC for each interleaving before the entire chain is recovered.<span style="mso-spacerun: yes">&nbsp; </span>During shutdown,<br />
 we bypass all this.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Just as we finalize objects that are reachable, we also drop all<br />
 references to unmanaged pUnks, even if they are reachable.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>From the perspective of managed code, at<br />
this point we are finished with the shutdown, though of course we perform many<br />
more steps for the unmanaged part of the shutdown.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There are a couple of points to note<br />
with the above steps.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l4 level1 lfo11; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>We never<br />
 unwind threads.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Every so often developers express their surprise that ‘catch’, ‘fault’,<br />
 ‘filter’ and ‘finally’ clauses haven’t executed throughout all their threads<br />
 as part of a shutdown.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>But we would be nuts to try this.<span style="mso-spacerun: yes">&nbsp; </span>It’s just too<br />
 disruptive to throw exceptions through threads to unwind them, unless we have<br />
 a compelling reason to do so (like AppDomain.Unload).<span style="mso-spacerun: yes">&nbsp; </span>And if those<br />
 threads contain unmanaged execution on their threads, the likelihood of<br />
 success is even lower.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>If we were on that plan, some small<br />
 percentage of attempted shutdowns would end up with “Unhandled Exception /<br />
 Debugger Attach” dialogs, for no good reason.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=2>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l4 level1 lfo11; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>Along the<br />
 same lines, developers sometimes express their surprise that all the<br />
 AppDomains aren’t unloaded before the process exits.<span style="mso-spacerun: yes">&nbsp; </span>Once again, the<br />
 benefits don’t justify the risk or the overhead of taking these extra<br />
 steps.<span style="mso-spacerun: yes">&nbsp; </span>If<br />
 you have termination code you must run, the ProcessExit event and Finalizable<br />
 objects should be sufficient for doing so.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1 start=3>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l4 level1 lfo11; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>We run most<br />
 of the above shutdown under the protection of a watchdog thread.<span style="mso-spacerun: yes">&nbsp; </span>By this I mean<br />
 that the shutdown thread signals the finalizer thread to perform most of the<br />
 above steps.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Then the shutdown thread enters a wait with a timeout.<span style="mso-spacerun: yes">&nbsp; </span>If the timeout<br />
 triggers before the finalizer thread has completed the next stage of the<br />
 managed shutdown, the shutdown thread wakes up and skips the rest of the<br />
 managed part of the shutdown.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>It does this by calling ExitProcess.<span style="mso-spacerun: yes">&nbsp; </span>This is almost<br />
 fool-proof.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Unfortunately, if the shutdown thread is an STA thread it will pump COM<br />
 messages (and SendMessages), while it is performing this watchdog blocking<br />
 operation.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>If it picks up a COM call into its STA that deadlocks, then the process<br />
 will hang.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>In a future release, we can fix this by using an extra thread.<span style="mso-spacerun: yes">&nbsp; </span>We’ve hesitated<br />
 to do so in the past because the deadlock is exceedingly rare, and because<br />
 it’s so wasteful to burn a thread in this manner.</font></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Finally, a lot more happens inside<br />
EEShutDown than the orderly managed steps listed above.<span style="mso-spacerun: yes">&nbsp; </span>We have some<br />
unmanaged shutdown that doesn’t directly impact managed execution.<span style="mso-spacerun: yes">&nbsp; </span>Even here we try<br />
hard to limit how much we do, particularly if we’re inside the OS loader<br />
lock.<span style="mso-spacerun: yes">&nbsp; </span>If we<br />
must shutdown inside the OS loader lock, we mostly just flush any logs we are<br />
writing and detach from trusted services like the profiler or<br />
debugger.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>One thing we do <i style="mso-bidi-font-style: normal">not</i> do during<br />
shutdown is any form of leak detection.<span style="mso-spacerun: yes">&nbsp; </span>This is somewhat controversial.<span style="mso-spacerun: yes">&nbsp; </span>There are a number<br />
of project teams at Microsoft which require a clean leak detection run whenever<br />
they shutdown.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And that sort of approach to leak detection has been formalized in<br />
services like MSVCRT’s _CrtDumpMemoryLeaks, for external use.<span style="mso-spacerun: yes">&nbsp; </span>The basic idea is<br />
that if you can find what you have allocated and release it, then you never<br />
really leaked it.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Conversely, if you cannot release it by the time you return from your<br />
DllMain then it’s a leak.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’m not a big fan of that approach to<br />
finding memory leaks, for a number of reasons:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l11 level1 lfo12; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>The fact<br />
 that you can reclaim memory doesn’t mean that you were productively using<br />
 it.<span style="mso-spacerun: yes">&nbsp; </span>For<br />
 example, the CLR makes extensive use of “loader heaps” that grow without<br />
 release until an AppDomain unloads.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>At that point, we discard the entire heap<br />
 without regard for the fine-grained allocations within it.<span style="mso-spacerun: yes">&nbsp; </span>The fact that we<br />
 remembered where all the heaps are doesn’t really say anything about whether<br />
 we leaked individual allocations within those heaps.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l11 level1 lfo12; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>In a few<br />
 well-bounded cases, we intentionally leak.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>For example, we often build little snippets<br />
 of machine code dynamically.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>These snippets are used to glue together<br />
 pieces of JITted code, or to check security, or twiddle the calling<br />
 convention, or various other reasons.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>If the circumstances of creation are rare<br />
 enough, we might not even synchronize threads that are building these<br />
 snippets.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Instead, we might use a light-weight atomic compare/exchange<br />
 instruction to install the snippet.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Losing the race means we must discard the<br />
 extra snippet.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>But if the snippet is small enough, the race is unlikely enough, and<br />
 the leak is bounded enough (e.g. we only need one such snippet per AppDomain<br />
 or process and reclaim it when the AppDomain or process terminates), then<br />
 leaking is perfectly reasonable.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>In that case, we may have allocated the<br />
 snippet in a heap that doesn’t support free’ing. </font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l11 level1 lfo12; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>This<br />
 approach certainly encourages a lot of messy code inside the<br />
 DLL_PROCESS_DETACH notification – which we all know is a very dangerous place<br />
 to write code.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>This is particularly true, given the way threads are wacked by the OS<br />
 at arbitrary points of execution.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Sure, all the OS CRITICAL_SECTIONs have<br />
 been weakened.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>But all the other synchronization primitives are still owned by those<br />
 wacked threads.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>And the weakened OS critical sections were supposed to protect data<br />
 structures that are now in an inconsistent state.<span style="mso-spacerun: yes">&nbsp; </span>If your shutdown<br />
 code wades into this landmine of deadlocks and trashed state, it will have a<br />
 hard time cleanly releasing memory blocks.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Projects often deal with this case by<br />
 keeping a count of all locks that are held.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>If this count is non-zero when we get our<br />
 DLL_PROCESS_DETACH notification, it isn’t safe to perform leak detection.<span style="mso-spacerun: yes">&nbsp; </span>But this leads to<br />
 concerns about how often the leak detection code is actually executed.<span style="mso-spacerun: yes">&nbsp; </span>For a while, we<br />
 considered it a test case failure if we shut down a process while holding a<br />
 lock.<span style="mso-spacerun: yes">&nbsp; </span>But<br />
 that was an insane requirement that was often violated in race<br />
 conditions.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l11 level1 lfo12; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>The OS is<br />
 about to reclaim all resources associated with this process.<span style="mso-spacerun: yes">&nbsp; </span>The OS will<br />
 perform a faster and more perfect job of this than the application ever<br />
 could.<span style="mso-spacerun: yes">&nbsp; </span>From<br />
 a product perspective, leak detection at product shutdown is about the least<br />
 interesting time to discover leaks.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l11 level1 lfo12; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2<br />
 >DLL_PROCESS_DETACH notifications are delivered to<br />
 different DLLs in a rather arbitrary order.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>I’ve seen DLLs either depend on brittle<br />
 ordering, or I’ve seen them make cross-DLL calls out of their DllMain in an<br />
 attempt to gain control over this ordering.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>This is all bad practice.<span style="mso-spacerun: yes">&nbsp; </span>However, I must<br />
 admit that in V1 of the CLR, fusion.dll &amp; mscorwks.dll played this “dance<br />
 of death” to coordinate their termination.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>Today, we’ve moved the Fusion code into<br />
 mscorwks.dll.</font>
 </li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; mso-list: l11 level1 lfo12; tab-stops: list.5in"<br />
 ><font face=Tahoma size=2>I think<br />
 it’s too easy for developers to confuse all the discipline surrounding this<br />
 approach with actually being leak-free.<span style="mso-spacerun: yes"<br />
 >&nbsp; </span>The approach is so onerous that the goal<br />
 quickly turns into satisfying the requirements rather than chasing<br />
 leaks.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There are at least two other ways to<br />
track leaks.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>One way is to identify scenarios that<br />
can be repeated, and then monitor for leaks during the steady-state of repeating<br />
those scenarios.<span style="mso-spacerun: yes">&nbsp;<br />
</span>For example, we have a test harness which can create an AppDomain, load<br />
an application into it, run it, unload the AppDomain, then rinse and<br />
repeat.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
first few times that we cycle through this operation, memory consumption<br />
increases.<span style="mso-spacerun: yes">&nbsp;<br />
</span>That’s because we actually JIT code and allocate data structures to<br />
support creating a 2<sup>nd</sup> AppDomain, or support<br />
making remote calls into the 2<sup>nd</sup> AppDomain, or<br />
support unloading that AppDomain.<span style="mso-spacerun: yes">&nbsp; </span>More subtly, the ThreadPool might create –<br />
and retain – a waiter thread or an IO thread.<span style="mso-spacerun: yes">&nbsp; </span>Or the application may trigger the creation<br />
of a new segment in the GC heap which the GC decides to retain even after the<br />
incremental contents have become garbage.<span style="mso-spacerun: yes">&nbsp; </span>This might happen because the GC decides it<br />
is not productive to perform a compacting collection at this time.<span style="mso-spacerun: yes">&nbsp; </span>Even the OS heap<br />
can make decisions about thread-relative look-aside lists or lazy VirtualFree<br />
calls.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But if you ignore the first 5 cycles of<br />
the application, and take a broad enough view over the next 20 cycles of the<br />
application, a trend becomes clear.<span style="mso-spacerun: yes">&nbsp; </span>And if you measure over a long enough period,<br />
paltry leaks of 8 or 12 bytes per cycle can be discovered.<span style="mso-spacerun: yes">&nbsp; </span>Indeed, V1 of the<br />
CLR shipped with a leak for a simple application in this test harness that was<br />
either 8 or 12 bytes (I can never remember which).<span style="mso-spacerun: yes">&nbsp; </span>Of that, 4 bytes<br />
was a known leak in our design.<span style="mso-spacerun: yes">&nbsp; </span>It was the data structure that recorded the<br />
IDs of all the AppDomains that had been unloaded.<span style="mso-spacerun: yes">&nbsp; </span>I don’t know if we’ve subsequently addressed<br />
that leak.<span style="mso-spacerun: yes">&nbsp; </span>But<br />
in the larger scheme of things, 8 or 12 bytes is pretty impressive.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Recently, one of our test developers has<br />
started experimenting with leak detection based on tracing of our unmanaged data<br />
structures.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Fortunately, many of these internal data structures are already described<br />
to remote processes, to support out-of-process debugging of the CLR.<span style="mso-spacerun: yes">&nbsp; </span>The idea is that we<br />
can walk out from the list of AppDomains, to the list of assemblies in each one,<br />
to the list of types, to their method tables, method bodies, field descriptors,<br />
etc.<span style="mso-spacerun: yes">&nbsp; </span>If we<br />
cannot reach all the allocated memory blocks through such a walk, then the<br />
unreachable blocks are probably leaks.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of course, it’s going to be much harder<br />
than it sounds.<span style="mso-spacerun: yes">&nbsp;<br />
</span>We twiddle bits of pointers to save extra state.<span style="mso-spacerun: yes">&nbsp; </span>We point to the<br />
interiors of heap blocks.<span style="mso-spacerun: yes">&nbsp; </span>We burn the addresses of some heap blocks,<br />
like dynamically generated native code snippets, into JITted code and then<br />
otherwise forget about the heap address.<span style="mso-spacerun: yes">&nbsp; </span>So it’s too early to say whether this<br />
approach will give us a sound mechanism for discovering leaks.<span style="mso-spacerun: yes">&nbsp; </span>But it’s certainly<br />
a promising idea and worth pursuing.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Rambling Security<br />
Addendum<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Finally, an off-topic note as I close<br />
down:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I haven’t blogged in about a month.<span style="mso-spacerun: yes">&nbsp; </span>That’s because I<br />
spent over 2 weeks (including weekends) on loan from the CLR team to the DCOM<br />
team.<span style="mso-spacerun: yes">&nbsp; </span>If<br />
you’ve watched the tech news at all during the last month, you can guess<br />
why.<span style="mso-spacerun: yes">&nbsp; </span>It’s<br />
security.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>From outside the company, it’s easy to<br />
see all these public mistakes and take a very frustrated attitude.<span style="mso-spacerun: yes">&nbsp; </span>“When will<br />
Microsoft take security seriously and clean up their act?”<span style="mso-spacerun: yes">&nbsp; </span>I certainly<br />
understand that frustration.<span style="mso-spacerun: yes">&nbsp; </span>And none of you want to hear me whine about<br />
how it’s unfair.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The company performed a much publicized<br />
and hugely expensive security push.<span style="mso-spacerun: yes">&nbsp; </span>Tons of bugs were filed and fixed.<span style="mso-spacerun: yes">&nbsp; </span>More importantly,<br />
the attitude of developers, PMs, testers and management was fundamentally<br />
changed.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Nobody on our team discusses new features without considering security<br />
issues, like building threat models.<span style="mso-spacerun: yes">&nbsp; </span>Security penetration testing is a fundamental<br />
part of a test plan.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Microsoft has made some pretty strong<br />
claims about the improved security of our products as a result of these<br />
changes.<span style="mso-spacerun: yes">&nbsp; </span>And<br />
then the DCOM issues come to light.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Unfortunately, it’s still going to be a<br />
long time before all our code is as clean as it needs to be.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Some of the code we reviewed in the DCOM<br />
stack had comments about DGROUP consolidation (remember that precious 64KB<br />
segment prior to 32-bit flat mode?) and OS/2 2.0 changes.<span style="mso-spacerun: yes">&nbsp; </span>Some of these<br />
source files contain comments from the ‘80s.<span style="mso-spacerun: yes">&nbsp; </span>I thought that Win95 was ancient!</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’ve only been at Microsoft for 6<br />
years.<span style="mso-spacerun: yes">&nbsp; </span>But<br />
I’ve been watching this company closely for a lot longer, first as a customer at<br />
Xerox and then for over a decade as a competitor at Borland and Oracle.<span style="mso-spacerun: yes">&nbsp; </span>For the greatest<br />
part of Microsoft’s history, the development teams have been focused on enabling<br />
as many scenarios as possible for their customers.<span style="mso-spacerun: yes">&nbsp; </span>It’s only been for<br />
the last few years that we’ve all realized that many scenarios should never be<br />
enabled.<span style="mso-spacerun: yes">&nbsp; </span>And<br />
many of the remainder should be disabled by default and require an explicit<br />
action to opt in.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>One way you can see this change in the<br />
company’s attitude is how we ship products.<span style="mso-spacerun: yes">&nbsp; </span>The default installation is increasingly<br />
impoverished.<span style="mso-spacerun: yes">&nbsp;<br />
</span>It takes an explicit act to enable fundamental goodies, like<br />
IIS.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Another hard piece of evidence that<br />
shows the company’s change is the level of resource that it is throwing at the<br />
problem.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Microsoft has been aggressively hiring security experts.<span style="mso-spacerun: yes">&nbsp; </span>Many are in a new<br />
Security Business Unit, and the rest are sprinkled through the product<br />
groups.<span style="mso-spacerun: yes">&nbsp; </span>Not<br />
surprisingly, the CLR has its own security development, PM, test and penetration<br />
teams.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I certainly wasn’t the only senior<br />
resource sucked away from his normal duties because of the DCOM alerts.<span style="mso-spacerun: yes">&nbsp; </span>Various folks from<br />
the Developer Division and Windows were handed over for an extended period.<span style="mso-spacerun: yes">&nbsp; </span>One of the other<br />
CLR architects was called back from vacation for this purpose.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We all know that Microsoft will remain a<br />
prime target for hacking.<span style="mso-spacerun: yes">&nbsp; </span>There’s a reason that everyone attacks<br />
Microsoft rather than Apple or Novell.<span style="mso-spacerun: yes">&nbsp; </span>This just means that we have to do a lot<br />
better.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Unfortunately, this stuff is still way<br />
too difficult.<span style="mso-spacerun: yes">&nbsp;<br />
</span>It’s a simple fact that only a small percentage of developers can write<br />
thread-safe free-threaded code.<span style="mso-spacerun: yes">&nbsp; </span>And they can only do it part of the<br />
time.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
state of the art for writing 100% secure code requires that same sort of<br />
super-human attention to detail.<span style="mso-spacerun: yes">&nbsp; </span>And a hacker only needs to find a single<br />
exploitable vulnerability.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I do think that managed code can avoid<br />
many of the security pitfalls waiting in unmanaged code.<span style="mso-spacerun: yes">&nbsp; </span>Buffer overruns are<br />
far less likely.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Our strong-name binding can guarantee that you call who you think you are<br />
calling.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Verifiable type safety and automatic lifetime management eliminate a<br />
large number of vulnerabilities that can often be used to mount security<br />
attacks.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Consideration of the entire managed stack makes simple luring attacks<br />
less likely.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Automatic flow of stack evidence prevents simple asynchronous luring<br />
attacks from succeeding.<span style="mso-spacerun: yes">&nbsp; </span>And so on.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But it’s <i style="mso-bidi-font-style: normal">still</i> way too<br />
hard.<span style="mso-spacerun: yes">&nbsp; </span>Looking<br />
forwards, a couple of points are clear:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l1 level1 lfo5; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>We need to focus harder on the goal that<br />
managed applications are secure, right out of the box.<span style="mso-spacerun: yes">&nbsp; </span>This means<br />
aggressively chasing the weaknesses of our present system, like the fact that<br />
locally installed assemblies by default run with FullTrust throughout their<br />
execution.<span style="mso-spacerun: yes">&nbsp; </span>It<br />
also means static and dynamic tools to check for security holes.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l1 level1 lfo5; tab-stops: list.5in"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><font face=Tahoma size=2>No matter what we do, hackers will find<br />
weak spots and attack them.<span style="mso-spacerun: yes">&nbsp; </span>The very best we can hope for is that we can<br />
make those attacks rarer and less effective.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’ll add managed security to my list for<br />
future articles.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma size=2></font></o></p>
<img src="http://blogs.msdn.com/aggbug.aspx?PostID=51504" width="1" height="1"/><br />
<span style="font-size:8pt; font-style:italic">http://blogs.msdn.com/cbrumme/archive/2003/08/20/51504.aspx</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/24/startup-shutdown-and-related-matters/feed/</wfw:commentRss>
	</item>
		<item>
		<title>ReflectionTypeLoadException</title>
		<link>http://cahtter.blogsome.com/2008/03/24/reflectiontypeloadexception/</link>
		<comments>http://cahtter.blogsome.com/2008/03/24/reflectiontypeloadexception/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 19:48:14 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/24/reflectiontypeloadexception/</guid>
		<description><![CDATA[	Also see: My Presidential Endorsement:
	Also see: Memory Model
	Also see: Brad Abrams&#8217; pixel8 Interview Podcast posted
	If a type can&#8217;t be loaded for some reason during a call to Module.GetTypes(), ReflectionTypeLoadException will be thrown. Assembly.GetTypes() also throws this because it calls Module.GetTypes(). 
	The Message for this exception is &#8220;One or more exceptions have been thrown while loading [...]]]></description>
			<content:encoded><![CDATA[	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/my-presidential-endorsement/"  title="My Presidential Endorsement:">My Presidential Endorsement:</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p>If a type can&#8217;t be loaded for some reason during a call to Module.GetTypes(), ReflectionTypeLoadException will be thrown. Assembly.GetTypes() also throws this because it calls Module.GetTypes(). </p>
	<p>The Message for this exception is &#8220;One or more exceptions have been thrown while loading the types&#8221; or &#8220;Unable to load one or more of the types in the assembly&#8221;, which doesn&#8217;t seem very descriptive. But, the exception actually provides more info that that. Just get the LoaderExceptions property of the ReflectionTypeLoadException instance. That will give an array of the exceptions caught while loading all of the types from the module. If the exceptions are due to an assembly loading problem, see my general debugging advice. </p>
<img src="http://blogs.msdn.com/aggbug.aspx?PostID=57236" width="1" height="1"/><br />
<span style="font-size:8pt; font-style:italic">http://blogs.msdn.com/suzcook/archive/2003/08/11/57236.aspx</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/24/reflectiontypeloadexception/feed/</wfw:commentRss>
	</item>
		<item>
		<title>Hosting</title>
		<link>http://cahtter.blogsome.com/2008/03/24/hosting/</link>
		<comments>http://cahtter.blogsome.com/2008/03/24/hosting/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 19:00:12 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/24/hosting/</guid>
		<description><![CDATA[	
	Also see: LINQ - The Uber FindControl
	Hosting
	< ?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />&nbsp;
	My prior three blogs were supposed to be on Hosting.&nbsp; Each time I got side tracked, first on Exceptions, then on Application Compatibility and finally on Finalization.&nbsp; I refuse to be side tracked this time&#8230; much.
	&nbsp;
	Also, I need to explain why [...]]]></description>
			<content:encoded><![CDATA[	<p><font face=Tahoma size=2></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Hosting</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">< ?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">My prior three blogs were supposed to be on Hosting.<span style="mso-spacerun: yes">&nbsp; </span>Each time I got side tracked, first on Exceptions, then on Application Compatibility and finally on Finalization.<span style="mso-spacerun: yes">&nbsp; </span>I refuse to be side tracked this time&#8230; much.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Also, I need to explain why it&#8217;s taken so long to get this blog out.<span style="mso-spacerun: yes">&nbsp; </span>Part of the reason is vacation.<span style="mso-spacerun: yes">&nbsp; </span>I spent Thanksgiving skiing in Whistler.<span style="mso-spacerun: yes">&nbsp; </span>Then I took a quick side trip to < ?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><st1 :City w:st="on"></st1><st1 :place w:st="on">Scottsdale</st1> for a friend&#8217;s surprise birthday party and to visit my parents.<span style="mso-spacerun: yes">&nbsp; </span>Finally, I spent over three weeks on Maui getting a break from the <st1 :place w:st="on"></st1><st1 :City w:st="on">Seattle</st1> winter.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p><a id="more-26"></a><br />
<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Another reason for the delay is writer&#8217;s block.<span style="mso-spacerun: yes">&nbsp; </span>This topic is so huge.<span style="mso-spacerun: yes">&nbsp; </span>The internal specification for the Whidbey Hosting Interfaces is over 100 pages.<span style="mso-spacerun: yes">&nbsp; </span>And that spec only covers the hosting interfaces themselves.<span style="mso-spacerun: yes">&nbsp; </span>There are many other aspects of hosting, like how to configure different security policy in different AppDomains, or how to use COM or managed C++ to stitch together the unmanaged host with the managed applications.<span style="mso-spacerun: yes">&nbsp; </span>There&#8217;s no way I can cover the entire landscape.</p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/bloggers-in-the-mavs-locker-room/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/java-design-operator-overloading-and-people/"  title="Java design, operator overloading and people">Java design, operator overloading and people</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/cool-silverlight-momentum-video-posted/"  title="Cool Silverlight Momentum Video Posted">Cool Silverlight Momentum Video Posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfroms-second-bind/"  title="LoadFrom's Second Bind">LoadFrom&#8217;s Second Bind</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/merry-christmas-indeed/"  title="Merry Christmas Indeed!">Merry Christmas Indeed!</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/my-presidential-endorsement/"  title="My Presidential Endorsement:">My Presidential Endorsement:</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/doing-the-deal-and-dishing-the-dirt/"  title="Doing the Deal and Dishing the Dirt">Doing the Deal and Dishing the Dirt</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/my-presidential-endorsement/"  title="My Presidential Endorsement:">My Presidential Endorsement:</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/devweek-2008-cross-platform-silverlight-demos/"  title="DevWeek 2008 Cross Platform Silverlight Demos">DevWeek 2008 Cross Platform Silverlight Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/note-to-self-blog-about-using-service-broker/"  title="Note to self: Blog about using Service Broker">Note to self: Blog about using Service Broker</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/access-to-old-blogs/"  title="Access to old blogs">Access to old blogs</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/cool-silverlight-momentum-video-posted/"  title="Cool Silverlight Momentum Video Posted">Cool Silverlight Momentum Video Posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/java-design-operator-overloading-and-people/"  title="Java design, operator overloading and people">Java design, operator overloading and people</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/my-presidential-endorsement/"  title="My Presidential Endorsement:">My Presidential Endorsement:</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/music-and-movies-give-away-the-soundtrack/"  title="Music and Movies - Give Away the Soundtrack">Music and Movies - Give Away the Soundtrack</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/compatability/"  title="Compatability">Compatability</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/cool-silverlight-momentum-video-posted/"  title="Cool Silverlight Momentum Video Posted">Cool Silverlight Momentum Video Posted</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Anyway, here goes. </p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Mostly I was tourist overhead at the PDC.<span style="mso-spacerun: yes">&nbsp; </span>But one of the places I tried to pay for my ticket was a panel on Hosting.<span style="mso-spacerun: yes">&nbsp; </span>The other panelists included a couple of Program Managers from the CLR, another CLR architect, representatives from Avalon / Internet Explorer, SQL Server, Visual Studio / Office, and &#8211; to my great pleasure &#8211; a representative from <st1 :mswterms w:st="on">IBM</st1> for DB2. </p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">One thing that was very clear at that panel is that the CLR team has done a poor job of defining what hosting is and how it is done.<span style="mso-spacerun: yes">&nbsp; </span>Depending on your definition, hosting could be:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo1; tab-stops: list.5in">Mixing unmanaged and managed code in the same process.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo1; tab-stops: list.5in">Running multiple applications, each in its own specially configured AppDomain.</li>
</ul>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Chat Software">Live Chat Software</a>: Next generation of Live Chat. On-Demand. Easy-to-Use.
</div>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo1; tab-stops: list.5in">Using the unmanaged hosting interfaces described in mscoree.idl.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l2 level1 lfo1; tab-stops: list.5in">Configuring how the CLR runs in the process, like disabling the concurrent GC through an application config file.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Even though the hosting interfaces described in mscoree.idl are a small part of what <i style="mso-bidi-font-style: normal">could</i> be hosting, I&#8217;m going to concentrate on those interfaces.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In V1 and V1.1 of the CLR, we provided some APIs that allowed an unmanaged process host to exercise some limited control over the CLR.<span style="mso-spacerun: yes">&nbsp; </span>This limited control included the ability to select the version of the CLR to load, the ability to create and configure AppDomains from unmanaged code, access to the ThreadPool, and a few other fundamental operations.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Custom Software Development">Custom Software</a> Development for Real-Estate, Hosting providers, Workflow and Business Management Systems.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Also, we knew we eventually needed to support hosts which manage all the memory in the process and which use non-preemptive scheduling of tasks and perhaps even light-weight fibers rather than OS threads.<span style="mso-spacerun: yes">&nbsp; </span>So we added some rudimentary (and alas inadequate) APIs for fibers and memory control.<span style="mso-spacerun: yes">&nbsp; </span>This invariably happens when you add features that you think you will eventually need, rather than features that someone is actually using and giving feedback on.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If you look closely at the V1 and V1.1 hosting APIs, you really see what we needed to support ASP.NET and a few other scenarios, like ones involving EnterpriseServices, Internet Explorer or VSA, plus some rudimentary guesses at what we might need to coexist properly inside SQL Server.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Obviously in Whidbey we have refined those guesses about SQL Server into hard requirements.<span style="mso-spacerun: yes">&nbsp; </span>And we tried very hard to generalize each extension that we added for SQL Server, so that it would be applicable to many other hosting scenarios.<span style="mso-spacerun: yes">&nbsp; </span>In fact, it&#8217;s amazing that the SQL Server team still talks to us &#8211; whenever they ask for anything, we always say No and give them something that works a lot better for other hosts and not nearly so well for SQL Server.</p>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Person Software">Live Person Software</a>: Turn website visitors into your customers.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/my-presidential-endorsement/"  title="My Presidential Endorsement:">My Presidential Endorsement:</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/compatability/"  title="Compatability">Compatability</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/music-and-movies-give-away-the-soundtrack/"  title="Music and Movies - Give Away the Soundtrack">Music and Movies - Give Away the Soundtrack</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/exception-handling-in-running-a-business/"  title="Exception Handling in Running a Business">Exception Handling in Running a Business</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/spring-web-flow-features-and-feedback-request/"  title="Spring Web Flow features and feedback request">Spring Web Flow features and feedback request</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/silverlight-2-beta-1-cross-domain-bug/"  title="Silverlight 2 Beta 1 Cross Domain Bug">Silverlight 2 Beta 1 Cross Domain Bug</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/spring-web-flow-features-and-feedback-request/"  title="Spring Web Flow features and feedback request">Spring Web Flow features and feedback request</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In our next release (Whidbey), we&#8217;ve made a real effort to clean up the existing hosting support and to dramatically extend it for a number of new scenarios.<span style="mso-spacerun: yes">&nbsp; </span>Therefore I&#8217;m not going to spend any more time discussing those original V1 &amp; V1.1 hosting APIs, except to the extent that they are still relevant to the following Whidbey hosting discussion.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Also I&#8217;m going to skip over all the general introductory topics like &#8220;When to host&#8221; since they were the source of my writer&#8217;s block.<span style="mso-spacerun: yes">&nbsp; </span>Instead, I&#8217;m going to leap into some of the more technically interesting topics.<span style="mso-spacerun: yes">&nbsp; </span>Maybe after we&#8217;ve studied various details we can step back and see some general guidelines.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">Threading and Synchronization<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">One of the most interesting challenges we struggled with during Whidbey was the need to cooperate with SQL Server&#8217;s task scheduling.<span style="mso-spacerun: yes">&nbsp; </span>SQL Server can operate in either thread mode or fiber mode.<span style="mso-spacerun: yes">&nbsp; </span>Most customers run in thread mode, but SQL Server can deliver its best numbers on machines with lots of CPUs when it&#8217;s running in fiber mode.<span style="mso-spacerun: yes">&nbsp; </span>That gap between thread and fiber mode has been closing as the OS addresses issues with its own preemptive scheduler.</p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Custom Software Solutions">Custom Software Solutions</a>. Billing and Invoicing Solutions, eCommerce and Website design.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfroms-second-bind/"  title="LoadFrom's Second Bind">LoadFrom&#8217;s Second Bind</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/spring-web-flow-features-and-feedback-request/"  title="Spring Web Flow features and feedback request">Spring Web Flow features and feedback request</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">A few years ago, I ran some experiments to see how many threads I could create in a single process.<span style="mso-spacerun: yes">&nbsp; </span>Not surprisingly, after almost 2000 threads I ran out of address space in the process.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because the default stack size on NT is 1 MB and the default user address space is 2 GB.<span style="mso-spacerun: yes">&nbsp; </span>(Starting with V1.1, the CLR can load into LARGEADDRESSAWARE processes and use up to 3 GB of address space).<span style="mso-spacerun: yes">&nbsp; </span>If you shrink the default stack size, you can create more than 2000 threads before hitting the address space limit.<span style="mso-spacerun: yes">&nbsp; </span>I see stack sizes of 256 KB in the SQL Server process on my machine, clearly to reduce this impact on process address space.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Of course, address space isn&#8217;t the only limit you can hit.<span style="mso-spacerun: yes">&nbsp; </span>Even on the 4 CPU server box I was experimenting with, the real memory on the system was inadequate for the working set being used.<span style="mso-spacerun: yes">&nbsp; </span>With enough threads, I exceeded real memory and experienced paging.<span style="mso-spacerun: yes">&nbsp; </span>(Okay, it was actually thrashing).<span style="mso-spacerun: yes">&nbsp; </span>But nowadays there are plenty of servers with several GB of real &#8211; and real cheap &#8211; memory, so this doesn&#8217;t have to be an issue.</p>
	<div class="interline">Multisoft Group: <a href="http://www.multisoftgroup.com/skills.html" title="Custom software solutions">Custom software solutions</a> for your business.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/fix-returnurl-when-sharing-forms-authentication-with-multiple-web-applications/"  title="Fix ReturnUrl When Sharing Forms Authentication with Multiple Web Applications">Fix ReturnUrl When Sharing Forms Authentication with Multiple Web Applications</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In my experiments, I simulated server request processing using an artificial work load that combined blocking, allocation, CPU-intensive computation, and a reasonable memory reference set using a mixture of both shared and per-request allocations.<span style="mso-spacerun: yes">&nbsp; </span>In the first experiments, all the threads were ready to run and all of them had equal priority.<span style="mso-spacerun: yes">&nbsp; </span>The result of this was that all threads were scheduled in a round-robin fashion on those 4 CPUs.<span style="mso-spacerun: yes">&nbsp; </span>Since the Windows OS schedules threads preemptively, each thread would execute until it either needed to block or it exceeded its quantum.<span style="mso-spacerun: yes">&nbsp; </span>With hundreds or even thousands of threads, each context switch was extremely painful.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because most of the memory used by that thread was so cold in the cache, having been fully displaced by the hundreds of threads that ran before it.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">As we all know, modern CPUs are getting faster and faster at raw computation.<span style="mso-spacerun: yes">&nbsp; </span>And they have more and more memory available to them.<span style="mso-spacerun: yes">&nbsp; </span>But access to that memory is getting relatively slower each year.<span style="mso-spacerun: yes">&nbsp; </span>By that, I mean that a single memory access costs the equivalent of an increasing number of instructions.<span style="mso-spacerun: yes">&nbsp; </span>One of the ways the industry tries to mitigate that relative slowdown is through a cache hierarchy.<span style="mso-spacerun: yes">&nbsp; </span>Modern X86 machines have L1, L2 and L3 levels of cache, ordered from fastest and smallest to slowest and largest.</p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Softwre Development">Softwre Development</a> for small and middle size companies. World-class software applications.
</div>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">(Other ways we try to mitigate the slowdown is by increasing the locality of our data structures and by pre-fetching.<span style="mso-spacerun: yes">&nbsp; </span>If you are a developer, hopefully you already know about locality.<span style="mso-spacerun: yes">&nbsp; </span>In the unmanaged world, locality is entirely your responsibility.<span style="mso-spacerun: yes">&nbsp; </span>In the managed world, you get some locality benefits from our environment &#8211; notably the garbage collector, but also the auto-layout of the class loader.<span style="mso-spacerun: yes">&nbsp; </span>Yet even in managed code, locality remains a major responsibility of each developer).</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Unfortunately, context switching between such a high number of threads will largely invalidate all those caches.<span style="mso-spacerun: yes">&nbsp; </span>So I changed my simulated server to be smarter about dispatching requests.<span style="mso-spacerun: yes">&nbsp; </span>Instead of allowing 1000 requests to execute concurrently, I would block 996 of those requests and allow 4 of them to run.<span style="mso-spacerun: yes">&nbsp; </span>This makes life pretty easy for the OS scheduler!<span style="mso-spacerun: yes">&nbsp; </span>There are four CPUs and four runnable threads.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s pretty obvious which threads should run.</p>
	<div class="interline">Developing <a href="http://www.multisoftgroup.com/projects.html" title="Customer Relationship Management ">Customer Relationship Management</a> Solutions. Web, e-Commerce, Database Design and Software Development.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/note-to-self-blog-about-using-service-broker/"  title="Note to self: Blog about using Service Broker">Note to self: Blog about using Service Broker</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/aspnet-mvc-in-codeplex-and-extensible-unit-testing/"  title="ASP.NET MVC in CodePlex and Extensible Unit Testing">ASP.NET MVC in CodePlex and Extensible Unit Testing</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/quaker-votes/"  title="Quaker votes">Quaker votes</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/compatability/"  title="Compatability">Compatability</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Not only will the OS keep those same four threads executing, it will likely keep them affinitized to the same CPUs.<span style="mso-spacerun: yes">&nbsp; </span>When a thread moves from one CPU to another, the new CPU needs to fill all the levels of cache with data appropriate to the new thread.<span style="mso-spacerun: yes">&nbsp; </span>However, if we can remain affinitized, we can enjoy all the benefits of a warm cache.<span style="mso-spacerun: yes">&nbsp; </span>The OS scheduler attempts to run threads on the CPU that last ran them (soft affinity).<span style="mso-spacerun: yes">&nbsp; </span>But in practice this soft affinity is too soft.<span style="mso-spacerun: yes">&nbsp; </span>Threads tend to migrate between CPUs far more than we would like.<span style="mso-spacerun: yes">&nbsp; </span>When the OS only has 4 runnable threads for its 4 CPUs, the amount of migration seemed to drop dramatically.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Incidentally, Windows also supports hard affinity.<span style="mso-spacerun: yes">&nbsp; </span>If a thread is hard affinitized to a CPU, it either runs on that CPU or it doesn&#8217;t run.<span style="mso-spacerun: yes">&nbsp; </span>The CLR can take advantage of this when the GC is executing in its server mode.<span style="mso-spacerun: yes">&nbsp; </span>But you have to be careful not to abuse hard affinity. You certainly don&#8217;t want to end up in a situation where all the &#8220;ready to run&#8221; threads are affinitized to one CPU and all the other CPUs are necessarily stalled.</p>
	<div class="interline"><a href="http://www.jbTop.com/" title="Help Desk Software">Help Desk Software</a>: Next generation of Live Chat. Jabber/XMPP Live Chat Service for your website.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/cool-silverlight-momentum-video-posted/"  title="Cool Silverlight Momentum Video Posted">Cool Silverlight Momentum Video Posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/mix-08-sessions-published/"  title="Mix 08 Sessions Published">Mix 08 Sessions Published</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Also, it&#8217;s worth mentioning the impact of hyper-threading or NUMA on affinity.<span style="mso-spacerun: yes">&nbsp; </span>On traditional SMP, our choices were pretty simple.<span style="mso-spacerun: yes">&nbsp; </span>Either our thread ran on its ideal processor, where we are most likely to see all the benefits of a warm cache, or it ran on some other processor.<span style="mso-spacerun: yes">&nbsp; </span>All those other processor choices can be treated as equally bad for performance.<span style="mso-spacerun: yes">&nbsp; </span>But with hyper-threading or NUMA, some of those other CPUs might be better choices than others.<span style="mso-spacerun: yes">&nbsp; </span>In the case of hyper-threading, some logical CPUs are combined into a single physical CPU and so they share access to the same cache memory at some level in the cache hierarchy.<span style="mso-spacerun: yes">&nbsp; </span>For NUMA, the CPUs may be arranged in partitions (e.g. hemispheres on some machines), where each partition has faster access to some memory addresses and slower access to other addresses.<span style="mso-spacerun: yes">&nbsp; </span>In all these cases, there&#8217;s some kind of gradient from the very best CPU(s) for a thread to execute on, down to the very worst CPU(s) for that particular thread.<span style="mso-spacerun: yes">&nbsp; </span>The world just keeps getting more interesting.</p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Custom Software Development">Custom Software</a> Development for Real-Estate, Hosting providers, Workflow and Business Management Systems.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/exception-handling-in-running-a-business/"  title="Exception Handling in Running a Business">Exception Handling in Running a Business</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Anyway, remember that my simulated server combined blocking with other operations.<span style="mso-spacerun: yes">&nbsp; </span>In a real server, that blocking could be due to a web page making a remote call to get rows from a database, or perhaps it could be blocking due to a web service request.<span style="mso-spacerun: yes">&nbsp; </span>If my server request dispatcher only allows 4 requests to be in flight at any time, such blocking will be a scalability killer.<span style="mso-spacerun: yes">&nbsp; </span>I would stall a CPU until my blocked thread is signaled.<span style="mso-spacerun: yes">&nbsp; </span>This would be intolerable.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Many servers address this issue by releasing some multiple of the ideal number of requests simultaneously.<span style="mso-spacerun: yes">&nbsp; </span>If I have 4 CPUs dedicated to my server process, then 4 requests is the ideal number of concurrent requests.<span style="mso-spacerun: yes">&nbsp; </span>If there&#8217;s &#8220;moderate&#8221; blocking during the processing of a typical request, I might find that 8 concurrent requests and 8 threads is a good tradeoff between more context switching and not stalling any CPUs.<span style="mso-spacerun: yes">&nbsp; </span>If I pick too high of a multiple over the number of CPUs, then context switching and cache effects will hurt my performance.<span style="mso-spacerun: yes">&nbsp; </span>If I pick too low a multiple, then blocking will stall a CPU and hurt my performance.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If you look at the heuristics inside the managed ThreadPool, you&#8217;ll find that we are constantly monitoring the CPU utilization.<span style="mso-spacerun: yes">&nbsp; </span>If we notice that some CPU resources are being wasted, we may be starving the system by not doing enough work concurrently.<span style="mso-spacerun: yes">&nbsp; </span>When this is detected, we are likely to release more threads from the ThreadPool in order to increase concurrency and make better use of the CPUs.<span style="mso-spacerun: yes">&nbsp; </span>This is a decent heuristic, but it isn&#8217;t perfect.<span style="mso-spacerun: yes">&nbsp; </span>For instance, CPU utilization is &#8220;backwards looking.&#8221;<span style="mso-spacerun: yes">&nbsp; </span>You actually have to stall a CPU before we will notice that more work should be executed concurrently.<span style="mso-spacerun: yes">&nbsp; </span>And by the time we&#8217;ve injected extra threads, the stalling situation may already have passed.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The OS has a better solution to this problem.<span style="mso-spacerun: yes">&nbsp; </span>IO Completion Ports have a direct link to the blocking primitives in Win32.<span style="mso-spacerun: yes">&nbsp; </span>When a thread is processing a work item from a completion port, if that thread blocks efficiently through the OS, then the blocking primitive will notify the completion port that it should release another thread.<span style="mso-spacerun: yes">&nbsp; </span>(Busy waiting instead of efficient blocking can therefore have a substantial impact on the amount of concurrency in the process).<span style="mso-spacerun: yes">&nbsp; </span>This feedback mechanism with IO Completion Ports is far more immediate and effective than the CLR&#8217;s heuristic based on CPU utilization.<span style="mso-spacerun: yes">&nbsp; </span>But in fairness I should point out that if a managed thread performs managed blocking via any of the managed blocking primitives (contentious Monitor.Enter, WaitHandle.WaitOne/Any/All, Thread.Join, GC.WaitForPendingFinalizers, etc.), then we have a similar feedback mechanism.<span style="mso-spacerun: yes">&nbsp; </span>We just don&#8217;t have hooks into the OS, so we cannot track all the blocking operations that occur in unmanaged code.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Of course, in my simulated server I didn&#8217;t have to worry about &#8220;details&#8221; like how to track all OS blocking primitives.<span style="mso-spacerun: yes">&nbsp; </span>Instead, I postulated a closed world where all blocking had to go through APIs exposed by my server.<span style="mso-spacerun: yes">&nbsp; </span>This gave me accurate and immediate information about threads either beginning to block or waking up from a blocking operation.<span style="mso-spacerun: yes">&nbsp; </span>Given this information, I was able to tweak my request dispatcher so it avoided any stalling by injecting new requests as necessary.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Although it&#8217;s possible to completely prevent stalling in this manner, it&#8217;s not possible to prevent context switches.<span style="mso-spacerun: yes">&nbsp; </span>Consider what happens on a 1 CPU machine.<span style="mso-spacerun: yes">&nbsp; </span>We release exactly one request which executes on one thread.<span style="mso-spacerun: yes">&nbsp; </span>When that thread is about to block, we release a second thread.<span style="mso-spacerun: yes">&nbsp; </span>So far, it&#8217;s perfect.<span style="mso-spacerun: yes">&nbsp; </span>But when the first thread resumes from its blocking operation, we now have two threads executing concurrently.<span style="mso-spacerun: yes">&nbsp; </span>Our request dispatcher can &#8220;retire&#8221; one of those threads as soon as it&#8217;s finished its work.<span style="mso-spacerun: yes">&nbsp; </span>But until then we have two threads executing on a single CPU and this will impact performance.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">I suppose we could try to get ruthless in this situation, perhaps by suspending one of the threads or reducing its priority.<span style="mso-spacerun: yes">&nbsp; </span>In practice, it&#8217;s never a good idea to suspend an executing thread.<span style="mso-spacerun: yes">&nbsp; </span>If that thread holds any locks that are required by other concurrent execution, we may have triggered a deadlock.<span style="mso-spacerun: yes">&nbsp; </span>Reducing the priority might help and I suspect I played around with that technique.<span style="mso-spacerun: yes">&nbsp; </span>To be honest, I can&#8217;t remember that far back.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">We&#8217;ll see that SQL Server can even solve this context switching problem.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">Oh yeah, SQL Server<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">So what does any of this have to do with SQL Server?</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Not surprisingly, the folks who built SQL Server know infinitely more than me about how to get the best performance out of a server.<span style="mso-spacerun: yes">&nbsp; </span>And when the CLR is inside SQL Server, it must conform to their efficient design.<span style="mso-spacerun: yes">&nbsp; </span>Let&#8217;s look at their thread mode, first.<span style="mso-spacerun: yes">&nbsp; </span>Fiber mode is really just a refinement over this.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Incoming requests are carried on threads.<span style="mso-spacerun: yes">&nbsp; </span>SQL Server handles a lot of simultaneous requests, so there are a lot of threads in the process.<span style="mso-spacerun: yes">&nbsp; </span>With normal OS &#8220;free for all&#8221; scheduling, this would result in way too many context switches, as we have seen.<span style="mso-spacerun: yes">&nbsp; </span>So instead those threads are affinitized to a host scheduler / CPU combination.<span style="mso-spacerun: yes">&nbsp; </span>The scheduler tries to ensure that there is one unblocked thread available at any time.<span style="mso-spacerun: yes">&nbsp; </span>All the other threads are ideally blocked.<span style="mso-spacerun: yes">&nbsp; </span>This gives us the nirvana of 100% busy CPUs and minimal context switches.<span style="mso-spacerun: yes">&nbsp; </span>To achieve this nirvana, all the blocking primitives need to cooperate with the schedulers.<span style="mso-spacerun: yes">&nbsp; </span>Even if an event has been signaled and a thread is considered by the application to be &#8220;ready to run&#8221;, the scheduler may not choose to release it, if the scheduler&#8217;s corresponding CPU is already executing another thread.<span style="mso-spacerun: yes">&nbsp; </span>In this manner, the blocking primitive and the scheduler are tightly integrated.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">When I built my simulated server, I was able to achieve an ideal &#8220;closed world&#8221; where all the synchronization primitives were controlled by me.<span style="mso-spacerun: yes">&nbsp; </span>SQL Server attempts the same thing.<span style="mso-spacerun: yes">&nbsp; </span>If a thread needs to block waiting for a data page to be read, or for a page or row latch to be released, that blocking occurs through the SQL Server scheduler.<span style="mso-spacerun: yes">&nbsp; </span>This guarantees that exactly one thread is available to run on each CPU, as we&#8217;ve seen.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Of course, execution of managed code also hits various blocking points.<span style="mso-spacerun: yes">&nbsp; </span>Monitor.Enter (&#8216;lock&#8217; in C# and &#8216;SyncLock&#8217; in VB.NET) is a typical case.<span style="mso-spacerun: yes">&nbsp; </span>Other cases include waiting for a GC to complete, waiting for class construction or assembly loading or type loading to occur, waiting for a method to be JITted, or waiting for a remote call or web service to return.<span style="mso-spacerun: yes">&nbsp; </span>For SQL Server to hit their performance goals and to avoid deadlocks, the CLR must route all of these blocking primitives to SQL Server (or any other similar host) through the new Whidbey hosting APIs.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">Leaving the Closed World<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">But what about synchronization primitives that are used for coordination with unmanaged code and which have precise semantics that SQL Server cannot hope to duplicate?<span style="mso-spacerun: yes">&nbsp; </span>For example, WaitHandle and its subtypes (like Mutex, AutoResetEvent and ManualResetEvent) are thin wrappers over the various OS waitable handles.<span style="mso-spacerun: yes">&nbsp; </span>These primitives provide atomicity guarantees when you perform a WaitAll operation on them.<span style="mso-spacerun: yes">&nbsp; </span>They have special behavior related to message pumping.<span style="mso-spacerun: yes">&nbsp; </span>And they can be used to coordinate activity across multiple processes, in the case of named primitives.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s unrealistic to route operations on WaitHandle through the hosting APIs to some equivalent host-provided replacements.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">This issue with WaitHandle is part of a more general problem.<span style="mso-spacerun: yes">&nbsp; </span>What happens if I PInvoke from managed code to an OS service like CoInitialize or LoadLibrary or CryptEncrypt?<span style="mso-spacerun: yes">&nbsp; </span>Do those OS services block?<span style="mso-spacerun: yes">&nbsp; </span>Well, I know that LoadLibrary will have to take the OS loader lock somewhere.<span style="mso-spacerun: yes">&nbsp; </span>I could imagine that CoInitialize might need to synchronize something, but I have no real idea.<span style="mso-spacerun: yes">&nbsp; </span>One thing I am sure of: if any blocking happens, it isn&#8217;t going to go through SQL Server&#8217;s blocking primitives and coordinate with their host scheduler.<span style="mso-spacerun: yes">&nbsp; </span>The idealized closed world that SQL Server needs has just been lost.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The solution here is to alert the host whenever a thread &#8220;leaves the runtime&#8221;.<span style="mso-spacerun: yes">&nbsp; </span>In other words, if we are PInvoking out, or making a COM call, or the thread is otherwise transitioning out to some unknown unmanaged execution, we tell the host that this is happening.<span style="mso-spacerun: yes">&nbsp; </span>If the host is tracking threads as closely as SQL Server does, it can use this event to disassociate the thread from the host scheduler and release a new thread.<span style="mso-spacerun: yes">&nbsp; </span>This ensures that the CPU stays busy.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because even if the disassociated thread blocks, we&#8217;ve released another thread.<span style="mso-spacerun: yes">&nbsp; </span>This newly released thread is still inside our closed world, so it will notify before it blocks so we can guarantee that the CPU won&#8217;t stall.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Wait a second.<span style="mso-spacerun: yes">&nbsp; </span>The CLR did a ton of work to re-route most of its blocking operations through the host.<span style="mso-spacerun: yes">&nbsp; </span>But we could have saved almost that entire ton of engineering effort if we had just detached the thread from the host whenever SQL Server called into managed code.<span style="mso-spacerun: yes">&nbsp; </span>That way, we could freely block and we wouldn&#8217;t disrupt the host&#8217;s scheduling decisions.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">This is true, but it won&#8217;t perform as well as the alternative. <span style="mso-spacerun: yes">&nbsp;</span>Whenever a thread disassociates from a host scheduler, another thread must be released.<span style="mso-spacerun: yes">&nbsp; </span>This guarantees that the CPU is busy, but it has sacrificed our nirvana of only having a single runnable thread per CPU.<span style="mso-spacerun: yes">&nbsp; </span>Now we&#8217;ve got two runnable threads for this CPU and the OS will be preemptively context-switching between them as they run out of quantum.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If a significant amount of the processing inside a host is performed through managed code, this would have a serious impact on performance.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Indeed, if a significant amount of the processing inside a host is performed in unmanaged code, called via PInvokes or COM calls or other mechanisms that &#8220;leave the runtime&#8221;, this too can have a serious impact on performance.<span style="mso-spacerun: yes">&nbsp; </span>But, for practical purposes, we expect most execution to remain inside the host or inside managed code.<span style="mso-spacerun: yes">&nbsp; </span>The amount of processing that happens in arbitrary unmanaged code should be low, especially over time as our managed platform grows to fill in some of the current gaps.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Of course, some PInvokes or COM calls might be to services that were exported from the host.<span style="mso-spacerun: yes">&nbsp; </span>We certainly don&#8217;t want to disassociate from the host scheduler every time the in-process <st1 :City w:st="on"></st1><st1 :place w:st="on">ADO</st1> provider performs a PInvoke back to SQL Server to get some data.<span style="mso-spacerun: yes">&nbsp; </span>This would be unnecessary and expensive.<span style="mso-spacerun: yes">&nbsp; </span>So there&#8217;s a way for the host to control which PInvoke targets perform a &#8220;leave runtime&#8221; / &#8220;return to runtime&#8221; pair and which ones are considered to remain within the closed world of our integrated host + runtime.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Even if we were willing to tolerate the substantial performance impact of considering all of the CLR to be outside the host&#8217;s closed world (i.e. we disassociated from the host&#8217;s scheduler whenever we ran managed code), this approach would be inadequate when running in fiber mode.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because of the nasty effects which thread affinity can have on a fiber-based system.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">Fiber Mode<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">As we&#8217;ve seen, SQL Server and other &#8220;extreme&#8221; hosts can ensure that at any time each CPU has only a single thread within the closed world that is ready to run.<span style="mso-spacerun: yes">&nbsp; </span>But when SQL Server is in thread mode, there are still a large number of threads that aren&#8217;t ready to run.<span style="mso-spacerun: yes">&nbsp; </span>It turns out that all those blocked threads impose a modest cost upon the OS preemptive scheduler.<span style="mso-spacerun: yes">&nbsp; </span>And that cost becomes an increasing consideration as the number of CPUs increases.<span style="mso-spacerun: yes">&nbsp; </span>For 1, 2, 4 and probably 8 CPU machines, fiber mode isn&#8217;t worth the headaches we&#8217;re about to discuss.<span style="mso-spacerun: yes">&nbsp; </span>But by the time you get to a larger machine, you might achieve something like a 20% throughput boost by switching to fiber mode.<span style="mso-spacerun: yes">&nbsp; </span>(I haven&#8217;t seen real numbers in a year or two, so please take that 20% as a vague ballpark).</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Fiber mode simply eliminates all those extra threads from any consideration by the OS.<span style="mso-spacerun: yes">&nbsp; </span>If you stay within the idealized nirvana (i.e. you don&#8217;t perform a &#8220;leave runtime&#8221; operation), there is only one thread for each host scheduler / CPU.<span style="mso-spacerun: yes">&nbsp; </span>Of course, there are many stacks / register contexts and each such stack / register context corresponds to an in-flight request.<span style="mso-spacerun: yes">&nbsp; </span>When a stack is ready to run, the single thread switches away from whatever stack it was running and switches to the new stack.<span style="mso-spacerun: yes">&nbsp; </span>But from the perspective of the OS scheduler, it just keeps running the only thread it knows about.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">So in both thread mode and fiber mode, SQL Server uses non-preemptive host scheduling of these tasks.<span style="mso-spacerun: yes">&nbsp; </span>This scheduling happens in user mode, which is a distinct advantage over the OS preemptive scheduling which happens in kernel mode.<span style="mso-spacerun: yes">&nbsp; </span>The only difference is whether the OS scheduler is aware of all the tasks on the host scheduler, or whether they all look like a single combined thread &#8211; albeit with different stacks and register contexts.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">But the impact of this difference is significant.<span style="mso-spacerun: yes">&nbsp; </span>First, it means that there is an M:N relationship between stacks (logical CLR threads) and OS threads.<span style="mso-spacerun: yes">&nbsp; </span>This is M:N because multiple stacks will execute on a single thread, and because the specially nominated thread that carries those stacks can change over time.<span style="mso-spacerun: yes">&nbsp; </span>This change in the nominated thread occurs as a consequence of those &#8220;leave runtime&#8221; calls.<span style="mso-spacerun: yes">&nbsp; </span>Remember that when a thread leaves the runtime, we inform the host which disassociates the thread from the host scheduler.<span style="mso-spacerun: yes">&nbsp; </span>A new thread is then created or obtained from a short list of already-created threads.<span style="mso-spacerun: yes">&nbsp; </span>This new thread then picks up the next stack that is ready to run.<span style="mso-spacerun: yes">&nbsp; </span>The effect is that this stack has migrated from the original disassociated thread to the newly nominated thread.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">This M:N relationship between stacks and OS threads causes problems everywhere that thread affinity would normally occur.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;ve already mentioned CPU affinity when discussing how threads are associated with CPUs.<span style="mso-spacerun: yes">&nbsp; </span>But now I&#8217;m talking about a different kind of affinity.<span style="mso-spacerun: yes">&nbsp; </span>Thread affinity is the association between various programmatic operations and the thread that these operations must run on.<span style="mso-spacerun: yes">&nbsp; </span>For example, if you take an OS critical section by calling EnterCriticalSection, the resulting ownership is tied to your thread.<span style="mso-spacerun: yes">&nbsp; </span>Sometimes developers say that the OS critical section is scoped to your thread.<span style="mso-spacerun: yes">&nbsp; </span>You must call LeaveCriticalSection from that same thread.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">None of this is going to work properly if your logical thread is asynchronously and apparently randomly migrating between different physical threads.<span style="mso-spacerun: yes">&nbsp; </span>You&#8217;ll successfully take the critical section on one logical thread.<span style="mso-spacerun: yes">&nbsp; </span>If you attempt to recursively acquire this critical section, you will deadlock if a migration has intervened.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because it will look like a different physical thread is actually the owner.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Imagine writing some hypothetical code inside the CLR:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'">EnterCriticalSection(pCS);<o :p></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><o :p>&nbsp;</o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'">If (pGlobalBlock == NULL)<o :p></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>pGlobalBlock = Alloc(count);<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><o :p>&nbsp;</o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'">LeaveCriticalSection(pCS);<o :p></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Obviously any real CLR code would be full of error handling, including a &#8216;finally&#8217; clause to release the lock.<span style="mso-spacerun: yes">&nbsp; </span>And we don&#8217;t use OS critical sections directly since we typically reflect them to an interested host as we&#8217;ve discussed.<span style="mso-spacerun: yes">&nbsp; </span>And we instrument a lot of this stuff, including spinning during lock acquisition.<span style="mso-spacerun: yes">&nbsp; </span>And we wrap the locks with lots of logic to avoid deadlocks, including GC-induced deadlocks.<span style="mso-spacerun: yes">&nbsp; </span>But let&#8217;s ignore all of the goop that would be necessary for real CLR code.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">It turns out that the above code has a thread affinity problem.<span style="mso-spacerun: yes">&nbsp; </span>Even though SQL Server&#8217;s fiber scheduling is non-preemptive, scheduling decisions can still occur whenever we call into the host.<span style="mso-spacerun: yes">&nbsp; </span>For reasons that I&#8217;ll explain later, all memory allocations in the CLR have the potential to call into the host and result in scheduling.<span style="mso-spacerun: yes">&nbsp; </span>Obviously most allocations will be satisfied locally in the CLR without escalation to the host.<span style="mso-spacerun: yes">&nbsp; </span>And most escalations to the host still won&#8217;t cause a scheduling decision to occur.<span style="mso-spacerun: yes">&nbsp; </span>But from a correctness perspective, all allocations have the potential to cause scheduling.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Other places where thread affinity can bite us include:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">The OS Mutex and the managed System.Threading.Mutex wrapper.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">LoadLibrary and DllMain interactions.<span style="mso-spacerun: yes">&nbsp; </span>As I&#8217;ve explained in my blog entry on Shutdown, DllMain notifications occur on a thread which holds the OS loader lock.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">TLS (thread local storage).<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s worth mentioning that, starting with Windows Server 2003, there are new FLS (fiber local storage) APIs.<span style="mso-spacerun: yes">&nbsp; </span>These APIs allow you to associate state with the logical rather than the physical thread.<span style="mso-spacerun: yes">&nbsp; </span>When a fiber is associated with a thread for execution (SwitchToFiber), the FLS is automatically moved from the fiber onto the thread.<span style="mso-spacerun: yes">&nbsp; </span>For managed TLS, we now move this automatically.<span style="mso-spacerun: yes">&nbsp; </span>But we cannot do this unconditionally for all the unmanaged TLS.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">Thread culture or locale, the impersonation context or user identity, the COM+ transaction context, etc.<span style="mso-spacerun: yes">&nbsp; </span>In some sense, these are just special cases of thread local storage.<span style="mso-spacerun: yes">&nbsp; </span>However, for historical reasons it isn&#8217;t possible to solve these problems by moving them to FLS.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">Taking control of a thread for GC, Abort, etc. via the OS SuspendThread() service.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">Any use of ThreadId or Thread Handle.<span style="mso-spacerun: yes">&nbsp; </span>This includes all debugging.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">&#8220;Hand-rolled&#8221; locks that we cannot discover or reason about, and which you have inadvertently based on the physical OS thread rather than the logical thread or fiber.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l3 level1 lfo2; tab-stops: list.5in">Various PInvokes or COM calls that might end up in unmanaged code with affinity requirements.<span style="mso-spacerun: yes">&nbsp; </span>For instance, MSHTML can only be called on STA threads which are necessarily affinitized.<span style="mso-spacerun: yes">&nbsp; </span>Of course, there is no list of all the APIs that have odd threading behavior.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s a minefield out there.</li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Solving affinity issues is relatively simple.<span style="mso-spacerun: yes">&nbsp; </span>The hard part is identifying all the places.<span style="mso-spacerun: yes">&nbsp; </span>Note that the last two bullet items are actually the application&#8217;s responsibility to identify.<span style="mso-spacerun: yes">&nbsp; </span>Some application code might appear to execute correctly when logical threads and OS threads are 1:1.<span style="mso-spacerun: yes">&nbsp; </span>But when a host creates an M:N relationship, any latent application bugs will be exposed.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In many cases, the easiest solution to a thread affinity issue is to disassociate the thread from the host&#8217;s scheduler until the affinity is no longer required.<span style="mso-spacerun: yes">&nbsp; </span>The hosting APIs provide for this, and we&#8217;ve taken care of it for you in many places &#8211; like System.Threading.Mutex.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="mso-spacerun: yes"></span>&nbsp;</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Before we finish our discussion of locking, there&#8217;s one more aspect worth mentioning.<span style="mso-spacerun: yes">&nbsp; </span>In an earlier blog, I have mentioned the limited deadlock detection and deadlock breaking which the CLR performs when executing class constructors or JITting.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Except for this limited case, the CLR doesn&#8217;t concern itself with application-level deadlocks.<span style="mso-spacerun: yes">&nbsp; </span>If you write some managed code that takes a set of locks in random order, resulting in a potential deadlock, we consider that to be your application bug.<span style="mso-spacerun: yes">&nbsp; </span>But some hosts may be more helpful.<span style="mso-spacerun: yes">&nbsp; </span>Indeed, SQL Server has traditionally detected deadlocks in all data accesses.<span style="mso-spacerun: yes">&nbsp; </span>When a deadlock occurs, SQL Server selects a victim and aborts the corresponding transaction.<span style="mso-spacerun: yes">&nbsp; </span>This allows the other requests implicated in the deadlock to proceed.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">With the new Whidbey hosting APIs, it&#8217;s possible for the host to walk all contentious managed locks and obtain a graph of the participants.<span style="mso-spacerun: yes">&nbsp; </span>This support extends to locking through our Monitor and our ReaderWriterLock.<span style="mso-spacerun: yes">&nbsp; </span>Clearly, an application could perform locking through other means.<span style="mso-spacerun: yes">&nbsp; </span>For example, an AutoResetEvent can be used to simulate mutual exclusion.<span style="mso-spacerun: yes">&nbsp; </span>But it&#8217;s not possible for such locks to be included in the deadlock algorithms, since there isn&#8217;t a strong notion of lock ownership that we can use.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Once the host has selected a deadlock victim, it must cause that victim to abort its forward progress somehow.<span style="mso-spacerun: yes">&nbsp; </span>If the victim is executing managed code, some obvious ways to do this include failing the lock attempt (since the thread is necessarily blocking), aborting the thread, or even unloading the AppDomain.<span style="mso-spacerun: yes">&nbsp; </span>We&#8217;ll return to the implications of this choice in the section on Reliability below.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Finally, it&#8217;s interesting to consider how one might get even better performance than what SQL Server has achieved.<span style="mso-spacerun: yes">&nbsp; </span>We&#8217;ve seen how fiber mode eliminates all the extra threads, by multiplexing a number of stacks / register contexts onto a single thread.<span style="mso-spacerun: yes">&nbsp; </span>What happens if we then eliminate all those fibers?<span style="mso-spacerun: yes">&nbsp; </span>For a dedicated server, we can achieve even better performance by forcing all application code to maintain its state outside of a thread&#8217;s stack.<span style="mso-spacerun: yes">&nbsp; </span>This allows us to use a single thread per CPU which executes user requests by processing them on its single dedicated stack.<span style="mso-spacerun: yes">&nbsp; </span>All synchronous blocking is eliminated by relying on asynchronous operations.<span style="mso-spacerun: yes">&nbsp; </span>The thread never yields while holding its stack pinned.<span style="mso-spacerun: yes">&nbsp; </span>The amount of memory required to hold an in-flight request will be far less than a 256 KB stack reservation.<span style="mso-spacerun: yes">&nbsp; </span>And the cost of processing an asynchronous completion through polling can presumably be less than the cost of a fiber context switch.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If all you care about is performance, this is an excellent way to build a server.<span style="mso-spacerun: yes">&nbsp; </span>But if you need to accommodate 3<sup>rd</sup> party applications inside the server, this approach is questionable.<span style="mso-spacerun: yes">&nbsp; </span>Most developers have a difficult time breaking their logic into segments which can be separately scheduled with no stack dependencies.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s a tedious programming model.<span style="mso-spacerun: yes">&nbsp; </span>Also, the underlying Windows platform still contains a lot of blocking operations that don&#8217;t have asynchronous variants available.<span style="mso-spacerun: yes">&nbsp; </span>WMI is one example.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">Memory Management<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Servers must not page.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Like all rules, this one isn&#8217;t strictly true.<span style="mso-spacerun: yes">&nbsp; </span>It is actually okay to page briefly now and then, when the work load transitions from one steady state to another.<span style="mso-spacerun: yes">&nbsp; </span>But if you have a server that is routinely paging, then you have driven that server beyond its capacity.<span style="mso-spacerun: yes">&nbsp; </span>You need to reduce the load on the server or increase the server&#8217;s memory capacity.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">At the same time, it&#8217;s important to make effective use of the memory capacity of a server.<span style="mso-spacerun: yes">&nbsp; </span>Ideally, a database would store the entire database contents in memory.<span style="mso-spacerun: yes">&nbsp; </span>This would allow it to avoid touching the disk, except to write the durable log that protects it from data loss and inconsistency in the face of catastrophic failure.<span style="mso-spacerun: yes">&nbsp; </span>Of course, the 2 or 3 GB limit of Win32 is far too restrictive for most interesting databases.<span style="mso-spacerun: yes">&nbsp; </span>(SQL Server can use AWE to escape this limit, at some cost).<span style="mso-spacerun: yes">&nbsp; </span>And even the address limits of Win64 are likely to be exceeded by databases presently.<span style="mso-spacerun: yes">&nbsp; </span>That&#8217;s because Win64 does not give you a full 64 bits of addressing and databases are already heading into the petabytes.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">So a database needs to consider all the competing demands for memory and make wise decisions about which ones to satisfy.<span style="mso-spacerun: yes">&nbsp; </span>Historically, those demands have included the buffer cache which contains data pages, compiled query plans, and all those thread stacks.<span style="mso-spacerun: yes">&nbsp; </span>When the CLR is loaded into the process, significant additional memory is required for the GC heap, application code, and the CLR itself.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;m not sure what techniques SQL Server uses to trade off the competing demands for memory.<span style="mso-spacerun: yes">&nbsp; </span>Some servers carve memory up based on fixed ratios for the different broad uses, and then rely on LRU within each memory chunk.<span style="mso-spacerun: yes">&nbsp; </span>Other servers assign a cost to each memory type, which indicates how expensive it would be to regenerate that memory.<span style="mso-spacerun: yes">&nbsp; </span>For example, in the case of a data page, that cost is an IO.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Some servers use elaborate throttling of inbound requests, to keep the memory load reasonable.<span style="mso-spacerun: yes">&nbsp; </span>This is relatively easy to do when all requests are comparable in terms of their memory and CPU requirements.<span style="mso-spacerun: yes">&nbsp; </span>But if some queries access a single database page and other queries touch millions of rows, it would be hard to factor this into a throttling decision that is so far upstream from the query processor.<span style="mso-spacerun: yes">&nbsp; </span>Instead, SQL Server tends to accept a large number of incoming requests and process them &#8220;concurrently.&#8221;<span style="mso-spacerun: yes">&nbsp; </span>We&#8217;ve already seen in great detail why this concurrent execution doesn&#8217;t actually result in preemptive context switching between all the corresponding tasks.<span style="mso-spacerun: yes">&nbsp; </span>But it is still the case that each request will hold onto some reference set of memory, even when the host&#8217;s non-preemptive scheduler has that request blocked.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If enough requests are blocked while holding onto significant unshared memory, then the server process may find itself over-committed on memory.<span style="mso-spacerun: yes">&nbsp; </span>At this point, it could page &#8211; which hurts performance.<span style="mso-spacerun: yes">&nbsp; </span>Or it could kill some of the requests and free up the resources they are holding onto.<span style="mso-spacerun: yes">&nbsp; </span>This is an unfortunate situation, because we&#8217;ve presumably already devoted resources like the CPU to get the request to its current state of partial completion.<span style="mso-spacerun: yes">&nbsp; </span>If we throw away the request, all that work was wasted.<span style="mso-spacerun: yes">&nbsp; </span>And the client is likely to resubmit the request, so we will have to repeat all that work soon.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Nevertheless, if the server is over-committed and it&#8217;s not practical to recover more memory by e.g. shrinking the number of pages devoted to the buffer cache, then killing in-flight requests is a sound strategy.<span style="mso-spacerun: yes">&nbsp; </span>This is particularly reasonable in database scenarios, since the transactional nature of database operations means that we can kill requests at any time and with impunity.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Unfortunately, the world of arbitrary managed execution has no transactional foundation we can rely on.<span style="mso-spacerun: yes">&nbsp; </span>We&#8217;ll pick up this issue again below, in the section on Reliability.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">It should be obvious that, if SQL Server or any other host is going to make wise decisions about memory consumption on a &#8220;whole process&#8221; basis, that host needs to know exactly how much memory is being used and for what purposes.<span style="mso-spacerun: yes">&nbsp; </span>For example, before the host unloads an AppDomain as a way of backing out of an over-committed situation, the host needs some idea of how many megabytes this unload operation is likely to deliver.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In the reverse direction, the host needs to be able to masquerade as the operating system.<span style="mso-spacerun: yes">&nbsp; </span>For instance, the CLR&#8217;s GC monitors system memory load and uses this information in its heuristics for deciding when to schedule a collection.<span style="mso-spacerun: yes">&nbsp; </span>The host needs a way to influence these collection decisions.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">SQL Server and ASP.NET<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Clearly a lot of work went into threading, synchronization and memory management in SQL Server.<span style="mso-spacerun: yes">&nbsp; </span>One obvious question to ask is how ASP.NET compares.<span style="mso-spacerun: yes">&nbsp; </span>They are both server products from Microsoft and they both execute managed code.<span style="mso-spacerun: yes">&nbsp; </span>Why didn&#8217;t we need to add all this support to the hosting interfaces in V1 of the CLR, so we could support ASP.NET?</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">I think it&#8217;s fair to say that ASP.NET took a much simpler approach to the problem of building a scalable server.<span style="mso-spacerun: yes">&nbsp; </span>To achieve efficient threading, they rely on the managed ThreadPool&#8217;s heuristics to keep the CPUs busy without driving up too many context switches.<span style="mso-spacerun: yes">&nbsp; </span>And since the bulk of memory allocations are due to the application, rather than the ASP.NET infrastructure (in other words, they aren&#8217;t managing large shared buffer pools for data pages), it&#8217;s not really possible for ASP.NET to act as a broker for all the different memory consumers.<span style="mso-spacerun: yes">&nbsp; </span>Instead, they just monitor the total memory load, and recycle the worker process if a threshold is exceeded.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">(Incidentally, V1 of ASP.NET and the CLR had an unfortunate bug with the selection of this threshold.<span style="mso-spacerun: yes">&nbsp; </span>The default point at which ASP.NET would recycle the process was actually a lower memory load than the point at which the CLR&#8217;s GC would switch to a more aggressive schedule of collections.<span style="mso-spacerun: yes">&nbsp; </span>So we were actually killing the worker process before the CLR had a chance to deliver more memory back to the application.<span style="mso-spacerun: yes">&nbsp; </span>Presumably in Whidbey this selection of default thresholds is now coordinated between the two systems.)</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">How can ASP.NET get away with this simpler approach?</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">It really comes down to their fundamental goals.<span style="mso-spacerun: yes">&nbsp; </span>ASP.NET can scale out, rather than having to scale up.<span style="mso-spacerun: yes">&nbsp; </span>If you have more incoming web traffic, you can generally throw more web servers at the problem and load balance between them.<span style="mso-spacerun: yes">&nbsp; </span>Whereas SQL Server can only scale out if the data supports this.<span style="mso-spacerun: yes">&nbsp; </span>In some cases, it does.<span style="mso-spacerun: yes">&nbsp; </span>There may be a natural partitioning of the data, like access to the HotMail mailbox for a particular incoming user.<span style="mso-spacerun: yes">&nbsp; </span>But in too many other cases, the data cannot be sufficiently partitioned and the server must be scaled up.<span style="mso-spacerun: yes">&nbsp; </span>On X86 Windows, the practical limit is a 32-way CPU with a hard limit of 3 GB of user address space.<span style="mso-spacerun: yes">&nbsp; </span>If you want to keep increasing your work load on a single box, you need to use every imaginative trick &#8211; like fibers or AWE &#8211; to eke out all possible performance.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">There&#8217;s also an availability issue.<span style="mso-spacerun: yes">&nbsp; </span>ASP.NET can recycle worker processes quite quickly.<span style="mso-spacerun: yes">&nbsp; </span>And if they have scaled out, recycling a worker process on one of the computers in the set will have no visible effect on the availability of the set of servers.<span style="mso-spacerun: yes">&nbsp; </span>But SQL Server may be limited to a single precious process.<span style="mso-spacerun: yes">&nbsp; </span>If that process must be recycled, the server is unavailable.<span style="mso-spacerun: yes">&nbsp; </span>And recycling a database is more expensive than recycling a stateless ASP.NET worker process, because transaction logs must be replayed to move the database forwards or backwards to a consistent state.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The short answer is, ASP.NET didn&#8217;t have to do all the high tech fancy performance work.<span style="mso-spacerun: yes">&nbsp; </span>Whereas SQL Server was forced down this path by the nature of the product they must build.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">Reliability<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Well, if you haven&#8217;t read my earlier blogs on asynchronous exceptions, or if &#8211; like me &#8211; you read the Reliability blog back in June and don&#8217;t remember what it said &#8211; you might want to review it quickly at http://blogs.msdn.com/cbrumme/archive/2003/06/23/51482.aspx.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The good news is that we&#8217;ve revisited the rules for ThreadAbortException in Whidbey, so that there is now a way to abort a thread without disturbing any backout code that it is currently running.<span style="mso-spacerun: yes">&nbsp; </span>But it&#8217;s still the case that asynchronous exceptions can intrude at fairly arbitrary spots in the execution.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Anyway, the availability goals of SQL Server place some rather difficult requirements on the CLR.<span style="mso-spacerun: yes">&nbsp; </span>Sure, we were pretty solid in V1 and V1.1.<span style="mso-spacerun: yes">&nbsp; </span>We ran a ton of stress and &#8211; if you avoided stack overflow, running out of memory, and any asynchronous exceptions like Thread.Abort &#8211; we could run applications indefinitely.<span style="mso-spacerun: yes">&nbsp; </span>We really were very clean.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">One problem with this is that &#8220;indefinitely&#8221; isn&#8217;t long enough for SQL Server.<span style="mso-spacerun: yes">&nbsp; </span>They have a noble goal of chasing 5 9&#8217;s and you can&#8217;t get there with loose statements like &#8220;indefinitely&#8221;.<span style="mso-spacerun: yes">&nbsp; </span>Another problem is that we can no longer exclude OutOfMemoryException and ThreadAbortException from our reliability profile.<span style="mso-spacerun: yes">&nbsp; </span>We&#8217;ve already seen that SQL Server tries to use 100% of memory, without quite triggering paging.<span style="mso-spacerun: yes">&nbsp; </span>The effect is that SQL Server is always on the brink of being out of memory, so allocation requests are frequently being denied.<span style="mso-spacerun: yes">&nbsp; </span>Along the same lines, if the server is loaded it will allow itself to become over-committed on all resources.<span style="mso-spacerun: yes">&nbsp; </span>One strategy for backing out of an over-commitment is to abort a thread (i.e. kill a transaction) or possibly unload one or more AppDomains.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Despite this stressful abuse, at no time can the process terminate.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The first step to achieve this was to harden the CLR so that it was resilient to any resource failures.<span style="mso-spacerun: yes">&nbsp; </span>Fortunately we have some extremely strong testers.<span style="mso-spacerun: yes">&nbsp; </span>One tester built a system to inject a resource failure in every allocator, for every unique logical call stack.<span style="mso-spacerun: yes">&nbsp; </span>This tests every distinct backout path in the product.<span style="mso-spacerun: yes">&nbsp; </span>This technique can be used for unmanaged and managed (FX) code.<span style="mso-spacerun: yes">&nbsp; </span>That same tester is also chasing any unmanaged leaks by applying the principles of a tracing garbage collector to our unmanaged CLR data structures.<span style="mso-spacerun: yes">&nbsp; </span>This technique has already exposed a small memory leak that we shipped in V1 of the CLR &#8211; for the &#8220;Hello World&#8221; application!</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">With testers like that, you better have a strong development team too.<span style="mso-spacerun: yes">&nbsp; </span>At this point, I think we&#8217;ve annotated the vast majority of our unmanaged CLR methods with reliability contracts.<span style="mso-spacerun: yes">&nbsp; </span>These are a bit like Eiffel pre- and post-conditions and they provide machine-verifiable statements about each method&#8217;s behavior with respect to GC, exceptions, and other fundamental operations.<span style="mso-spacerun: yes">&nbsp; </span>These contracts can be used during test coverage (and, in some cases, during static scans of the binary images) to test for conformance.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The bottom line is that the next release of CLR should be substantially more robust in the face of resource errors.<span style="mso-spacerun: yes">&nbsp; </span>Leaving aside stack overflows and focusing entirely on the unmanaged runtime, we are shooting for perfection.<span style="mso-spacerun: yes">&nbsp; </span>Even for stack overflow, we expect to get very, very close.<span style="mso-spacerun: yes">&nbsp; </span>And we have the mechanisms in place that allow us to be rigorous in chasing after these goals.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">But what about all of the managed code?</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Will FX be as robust as the unmanaged CLR?<span style="mso-spacerun: yes">&nbsp; </span>And how can we possibly hold 3<sup>rd</sup> party authors of stored procedures or user defined functions to that same high bar?<span style="mso-spacerun: yes">&nbsp; </span>We want to enable a broad class of developers to write this sort of code, and we cannot expect them to perform many hundreds of hours of stress testing and fault injection on each new stored procedure.<span style="mso-spacerun: yes">&nbsp; </span>If we&#8217;re chasing 5 9&#8217;s by requiring every external developer to write perfect code, we should just give up now.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Instead, SQL Server relies on something other than perfect code.<span style="mso-spacerun: yes">&nbsp; </span>Consider how SQL Server worked before it started hosting the CLR:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The vast majority of execution inside SQL Server was via Transact SQL or TSQL.<span style="mso-spacerun: yes">&nbsp; </span>Any application written in TSQL is inherently scalable, fiber-aware, and robust in the face of resource errors.<span style="mso-spacerun: yes">&nbsp; </span>Any computation in TSQL can be terminated with a clean transaction abort.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Unfortunately, TSQL isn&#8217;t expressive enough to satisfy all application needs.<span style="mso-spacerun: yes">&nbsp; </span>So the remaining applications were written in extended stored procedures or xprocs.<span style="mso-spacerun: yes">&nbsp; </span>These are typically unmanaged C++.<span style="mso-spacerun: yes">&nbsp; </span>Their authors must be extremely sophisticated, because they are responsible for integrating their execution with the unusual threading environment and resource rules that exist inside SQL Server.<span style="mso-spacerun: yes">&nbsp; </span>Throw in the rules for data access and security (which I won&#8217;t be discussing in this blog) and it takes superhuman knowledge and skill to develop a bug-free xproc. </p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In other words, you had a choice of well-behaved execution and limited expression (TSQL), or the choice of arbitrary execution coupled with a very low likelihood that you would get it right (xprocs).</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">One of the shared goals of the SQL Server and CLR teams in Whidbey was to eliminate the need for xprocs.<span style="mso-spacerun: yes">&nbsp; </span>We wanted to provide a spectrum of choices to managed applications.<span style="mso-spacerun: yes">&nbsp; </span>In Whidbey, that spectrum consists of three buckets for managed code:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l0 level1 lfo3; tab-stops: list.5in"><b>Safe<o :p></o></b></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in">Code in this bucket is the most constrained. <span style="mso-spacerun: yes">&nbsp;</span>In fact, the host constrains it beyond what the CLR would normally allow to code that&#8217;s only granted SecurityPermissionFlag.Execution.<span style="mso-spacerun: yes">&nbsp; </span>So this code must be verifiably typesafe and has a reduced grant set.<span style="mso-spacerun: yes">&nbsp; </span>But it is further constrained from defining mutable static fields, from creating or controlling threads, from using the threadpool, etc.<span style="mso-spacerun: yes">&nbsp; </span>The goal here is to guide the code to best practices for scalability and robustness within the SQL Server or similar hosted environments.<span style="mso-spacerun: yes">&nbsp; </span>In the case of SQL Server, this means that all state should be stored in the database and that concurrency is controlled through transactions against the data.<span style="mso-spacerun: yes">&nbsp; </span>However, it&#8217;s important to realize that these additional constraints are not part of the Security system and they may well be subvertible.<span style="mso-spacerun: yes">&nbsp; </span>The constraints are simply speedbumps (not roadblocks) which guide the application code away from potentially non-scalable coding techniques and which encourage best practices.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l0 level1 lfo3; tab-stops: list.5in"><b>External Access<o :p></o></b></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in">Code in this bucket should be sufficient for replacing most xprocs.<span style="mso-spacerun: yes">&nbsp; </span>Such code must also be verifiably typesafe, but it is granted some additional permissions.<span style="mso-spacerun: yes">&nbsp; </span>The exact set of permissions is presumably subject to change until <st1 :State w:st="on"></st1><st1 :place w:st="on">Yukon</st1> ships, but it&#8217;s likely to allow access to the registry, the file system, and the network.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal style="MARGIN: 0in 0in 0pt; mso-list: l0 level1 lfo3; tab-stops: list.5in"><b>Unsafe<o :p></o></b></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in">This is the final managed escape hatch for writing code inside SQL Server.<span style="mso-spacerun: yes">&nbsp; </span>This code does not have to be verifiable.<span style="mso-spacerun: yes">&nbsp; </span>It has FullTrust (with the possible exception of UIPermission, which makes no sense within the database).<span style="mso-spacerun: yes">&nbsp; </span>This means that it can do anything the most arbitrary xproc can do.<span style="mso-spacerun: yes">&nbsp; </span>However, it is much more likely to work properly, compared to that xproc.<span style="mso-spacerun: yes">&nbsp; </span>First, it sits on top of a framework that has been designed to work inside the database.<span style="mso-spacerun: yes">&nbsp; </span>Second, the code has all the usual benefits of managed code, like a memory manager that&#8217;s based on accurate reachability rather than on programmer correctness.<span style="mso-spacerun: yes">&nbsp; </span>Finally, it is executing on a runtime that understands the host&#8217;s special rules for resource management, synchronization, threading, security, etc.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">For code in the Safe bucket, you may be wondering how a host could constrain code beyond SecurityPermissionFlag.Execution.<span style="mso-spacerun: yes">&nbsp; </span>There are two techniques available for this:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l1 level1 lfo4; tab-stops: list.5in"><span style="mso-bidi-font-family: Tahoma; mso-fareast-font-family: Tahoma"></span><span style="mso-list: Ignore">1)</span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>Any assembly in the &#8216;Safe&#8217; subset could be scanned by a host-provided pre-verifier, to check for any questionable programming constructs like the definition of mutable static fields, or the use of reflection.<span style="mso-spacerun: yes">&nbsp; </span>This raises the obvious question of how the host can interject itself into the binding process and guarantee that only pre-verified assemblies are loaded.<span style="mso-spacerun: yes">&nbsp; </span>The new Whidbey hosting APIs contain a Fusion loader hook mechanism, which allows the host to abstract the notion of an assembly store, without disturbing all our normal loader policy.<span style="mso-spacerun: yes">&nbsp; </span>You can think of this as the natural evolution of the AppDomain.AssemblyResolve event.<span style="mso-spacerun: yes">&nbsp; </span>SQL Server can use this mechanism to place all application assemblies into the database and then deliver them to the loader on demand.<span style="mso-spacerun: yes">&nbsp; </span>In addition to enabling pre-verification, the loader hooks can also be used to ensure that applications inside the database are not inadvertently broken or influenced by changes outside the database (e.g. changes to the GAC).<span style="mso-spacerun: yes">&nbsp; </span>In fact, you could even copy a database from one machine to another and theoretically this could automatically transfer all the assemblies required by that database.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; mso-list: l1 level1 lfo4; tab-stops: list.5in"><span style="mso-bidi-font-family: Tahoma; mso-fareast-font-family: Tahoma"></span><span style="mso-list: Ignore">2)</span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>The Whidbey hosting APIs provide controls over a new Host Protection Attribute (HPA) feature.<span style="mso-spacerun: yes">&nbsp; </span>Throughout our frameworks, we&#8217;ve decorated various unprotected APIs with an appropriate HPA.<span style="mso-spacerun: yes">&nbsp; </span>These HPAs indicate that the decorated API performs a sensitive operation like Synchronization or Thread Control.<span style="mso-spacerun: yes">&nbsp; </span>For instance, use of the ThreadPool isn&#8217;t considered a secure operation.<span style="mso-spacerun: yes">&nbsp; </span>(At some level, it is a risk for Denial of Service attacks, but DOS remains an open design topic for our managed platform).<span style="mso-spacerun: yes">&nbsp; </span>If code is running outside of a host that enables these HPAs, they have no effect.<span style="mso-spacerun: yes">&nbsp; </span>Partially trusted code, including code that only has Execution permission, can still call all these APIs.<span style="mso-spacerun: yes">&nbsp; </span>But if a host does enable these attributes, then code with insufficient trust can no longer call these APIs directly.<span style="mso-spacerun: yes">&nbsp; </span>Indirect calls are still permitted, and in this sense the HPA mechanism is similar to the mechanism for LinkDemands.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Although HPAs use a mechanism that is similar to LinkDemands, it&#8217;s very important to distinguish the HPA feature &#8211; which is all about programming model guidance &#8211; from any Security feature.<span style="mso-spacerun: yes">&nbsp; </span>A great way to illustrate this distinction is Monitor.Enter.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Ignoring HPAs, any code can call Monitor.Enter and use this API to synchronize with other threads.<span style="mso-spacerun: yes">&nbsp; </span>Naturally, SQL Server would prefer that most developers targeting their environment (including all the na&#239;ve ones) should rely on database locks under transaction control for this sort of thing.<span style="mso-spacerun: yes">&nbsp; </span>Therefore they activate the HPA on this class:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span>[<span style="COLOR: red">HostProtection(Synchronization=true, ExternalThreading=true)</span>]<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span>public sealed class Monitor <o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span>{<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>&#8230;<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>[MethodImplAttribute(MethodImplOptions.InternalCall)]<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>public static extern void <span style="COLOR: red">Enter</span>(Object obj);<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">However, devious code in the &#8216;Safe&#8217; bucket could use a HashTable as an alternate technique for locking.<span style="mso-spacerun: yes">&nbsp; </span>If you create a synchronized HashTable and then perform inserts or lookups, your Object.Equals and GetHashCode methods will be called within the lock that synchronizes the HashTable.<span style="mso-spacerun: yes">&nbsp; </span>The BCL developers were smart enough to realize this, and they added another HPA:</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span>public class Hashtable : IDictionary, ISerializable,<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="mso-spacerun: yes">&nbsp;</span>IDeserializationCallback, ICloneable<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span>{<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>&#8230;<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: red">[HostProtection(Synchronization=true)]<o :p></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>public static Hashtable <span style="COLOR: red">Synchronized</span>(Hashtable table) {<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>if (table==null)<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>throw new ArgumentNullException(&#8221;table&#8221;);<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>return new SyncHashtable(table);<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"></span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>}<o :p></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Are there other places inside the frameworks where it&#8217;s possible to trick an API into providing synchronization for its caller?<span style="mso-spacerun: yes">&nbsp; </span>Undoubtedly there are, but we aren&#8217;t going to perform exhaustive audits of our entire codebase to discover them all.<span style="mso-spacerun: yes">&nbsp; </span>As we find additional APIs, we will decorate them with HPAs, but we make no guarantees here.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">This would be an intolerable situation for a Security feature, but it&#8217;s perfectly acceptable when we&#8217;re just trying to increase the scalability and reliability of naively written database applications.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b>Escalation Policy<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">I chose the HPA on System.Threading.Monitor for a reason, in the above example.<span style="mso-spacerun: yes">&nbsp; </span>If you&#8217;ve read my earlier blogs on Thread.Abort, you know that it&#8217;s dangerous to asynchronously abort another thread.<span style="mso-spacerun: yes">&nbsp; </span>That thread could be executing a class constructor, in which case that class is now unavailable throughout the AppDomain.<span style="mso-spacerun: yes">&nbsp; </span>That thread could be in the middle of an update to some shared application state, which would leave the application in an inconsistent state.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In V1 &amp; V1.1, it was not really possible to write code that is robust in the face of asynchronous exceptions like Abort.<span style="mso-spacerun: yes">&nbsp; </span>In Whidbey, we&#8217;re now introducing some constructs (Constrained Execution Regions and Critical Finalization) which make it possible to do this.<span style="mso-spacerun: yes">&nbsp; </span>I&#8217;m not going to discuss those constructs in this blog.<span style="mso-spacerun: yes">&nbsp; </span>But suffice it to say that, although it makes it possible to write entirely robust code, it doesn&#8217;t make it easy.<span style="mso-spacerun: yes">&nbsp; </span>Without a higher level programmatic construct, like transactions, it&#8217;s very difficult to write entirely robust code.<span style="mso-spacerun: yes">&nbsp; </span>You must acquire all the resources required for forward progress, tolerating exceptions during this acquisition phase.<span style="mso-spacerun: yes">&nbsp; </span>Then you enter a forward progress phase, which either cannot fail or which unconditionally triggers some compensating backout code upon failure.<span style="mso-spacerun: yes">&nbsp; </span>If compensation is triggered, it must guarantee that the system is returned to a consistent state before it completes.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If you&#8217;ve successfully written that sort of code, you know that it&#8217;s an onerous discipline.<span style="mso-spacerun: yes">&nbsp; </span>There&#8217;s no way that we can expect the greater population of developers to write large bodies of bug-free code based on this plan.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">That&#8217;s why, in V1 &amp; V1.1, we recommend either using Abort on the current thread (in which case it is not asynchronous) or we recommend using it in conjunction with an AppDomain.Unload (in which case any inconsistent application state is likely to be discarded).</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In Whidbey, it is possible to avoid inducing asynchronous Aborts onto threads that are performing backout (i.e. filter, finally, catch or fault blocks) or that hold locks.<span style="mso-spacerun: yes">&nbsp; </span>Our definition of a lock is pretty broad.<span style="mso-spacerun: yes">&nbsp; </span>It includes execution of a class constructor, since all.cctor execution is synchronized according to elaborate rules by the CLR.<span style="mso-spacerun: yes">&nbsp; </span>It also includes Monitor.Enter, Mutex, ReaderWriterLock, etc.<span style="mso-spacerun: yes">&nbsp; </span>Finally, it includes any &#8220;hand-rolled&#8221; locks that you build, so long as you properly identify them to us.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Our rationale here is that any thread holding a lock may be updating shared state.<span style="mso-spacerun: yes">&nbsp; </span>If a thread isn&#8217;t holding a lock, then any update it performs against shared state must be atomic or at least it never leaves that shared state in an inconsistent state.<span style="mso-spacerun: yes">&nbsp; </span>This is strictly a heuristic, but it&#8217;s a pretty good one.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If we believe this heuristic, it means that we can use Abort without consequently unloading an AppDomain, if that thread doesn&#8217;t hold any locks and isn&#8217;t performing any backout.<span style="mso-spacerun: yes">&nbsp; </span>And it just so happens that the bulk of all managed code executing inside SQL Server is in the &#8216;Safe&#8217; subset &#8211; which coincidentally is highly discouraged via HPAs from taking or holding locks.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In other words, code in the &#8216;Safe&#8217; subset can almost always take an asynchronous exception without affecting any of the execution on other threads in the same AppDomain.<span style="mso-spacerun: yes">&nbsp; </span>This is the case, even though that code was written by developers who don&#8217;t understand the deep issues involved with asynchronous exceptions.<span style="mso-spacerun: yes">&nbsp; </span>It further means that if we should catch such a thread at a point where it isn&#8217;t safe to inject an asynchronous exception without also unloading the AppDomain, we can identify this window.<span style="mso-spacerun: yes">&nbsp; </span>Once this window is identified, we can either hold off from injecting the exception until this unsafe window has closed, or we can unload the entire AppDomain to eliminate the application inconsistency.<span style="mso-spacerun: yes">&nbsp; </span>The host can decide whether to hold off on the injection or alternatively to proceed with an AppDomain unload, based on criteria like how resource-constrained the host is.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">The hosting APIs for making these decisions imperatively would be rather complicated.<span style="mso-spacerun: yes">&nbsp; </span>So the Whidbey hosting APIs provide a declarative mechanism called an escalation policy.<span style="mso-spacerun: yes">&nbsp; </span>This allows the host to express transitions and timeouts that take effect during error conditions.<span style="mso-spacerun: yes">&nbsp; </span>For instance, SQL Server might state that any attempt to Abort a thread should delay if the victim thread holds a lock.<span style="mso-spacerun: yes">&nbsp; </span>But if that delay exceeds 30 seconds, the Abort attempt should be escalated to an AppDomain.Unload.<span style="mso-spacerun: yes">&nbsp; </span>Of course, the feature is more general than SQL Server&#8217;s needs.<span style="mso-spacerun: yes">&nbsp; </span>Indeed, the V1 ASP.NET process recycling feature should now be expressible as a particular Whidbey escalation policy.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal">Winding down<o :p></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">As usual, I didn&#8217;t get around to many of the interesting topics.<span style="mso-spacerun: yes">&nbsp; </span>For instance, those guidelines on when and how to host are noticeably absent.<span style="mso-spacerun: yes">&nbsp; </span>And I didn&#8217;t explain how to do any simple stuff, like picking concurrent vs. non-concurrent vs. server GC.<span style="mso-spacerun: yes">&nbsp; </span>The above text is completely free of any specific details of what our hosting APIs look like (partly because they are subject to change until Whidbey ships).<span style="mso-spacerun: yes">&nbsp; </span>And I didn&#8217;t touch on any hosting topics outside of the hosting APIs, like all of the AppDomain considerations.<span style="mso-spacerun: yes">&nbsp; </span>As you can imagine, there&#8217;s also plenty I could have said about Security.<span style="mso-spacerun: yes">&nbsp; </span>For instance, the hosting APIs allow the host to participate in role-based security and impersonation of Windows identities&#8230;<span style="mso-spacerun: yes">&nbsp; </span>Oh well.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Fortunately, one of the PMs involved in the Whidbey hosting effort is apparently writing a book on the general topic of hosting.<span style="mso-spacerun: yes">&nbsp; </span>Presumably all these missing topics will be covered there.<span style="mso-spacerun: yes">&nbsp; </span>And hopefully he won&#8217;t run into the same issues with writer&#8217;s block that I experienced on this topic.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">(Indeed, the event that ultimately resolved my writer&#8217;s block was that my wife got the flu.<span style="mso-spacerun: yes">&nbsp; </span>When she&#8217;s not around, my weekends are boring enough for me to think about work.<span style="mso-spacerun: yes">&nbsp; </span>The reason I&#8217;m posting two blogs this weekend is that Kathryn has gone to <st1 :place w:st="on">Maui</st1> for the week and has left me behind.)</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Finally, the above blog talks about SQL Server a lot.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Hopefully it&#8217;s obvious that the CLR wants to be a great execution environment for a broad set of servers.<span style="mso-spacerun: yes">&nbsp; </span>In V1, we focused on ASP.NET.<span style="mso-spacerun: yes">&nbsp; </span>Based on that effort, we automatically worked well in many other servers with no additional work.<span style="mso-spacerun: yes">&nbsp; </span>For example, EnterpriseServices dropped us into their server processes simply by selecting the server mode of our GC.<span style="mso-spacerun: yes">&nbsp; </span>Nothing else was required to get us running efficiently.<span style="mso-spacerun: yes">&nbsp; </span>(Well, we did a ton of other work in the CLR to support EnterpriseServices.<span style="mso-spacerun: yes">&nbsp; </span>But that work was related to the COM+ programming model and infrastructure, rather than their server architecture.<span style="mso-spacerun: yes">&nbsp; </span>We had to do that work whether we ran in their server process or were instead loading EnterpriseServices into the ASP.NET worker process or some other server).</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">In Whidbey we focused on extending the CLR to meet SQL Server&#8217;s needs.<span style="mso-spacerun: yes">&nbsp; </span>But at every opportunity we generalized SQL Server&#8217;s requirements and tried to build something that would be more broadly useful.<span style="mso-spacerun: yes">&nbsp; </span>Just as our ASP.NET work enabled a large number of base server hosting scenarios, we hope that our SQL Server work will enable a large number of advanced server hosting scenarios.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">If you have a &#8220;commercially significant&#8221; hosting problem, whether on the server or the client, and you&#8217;re struggling with how to incorporate managed code, I would be interested in hearing from you directly.<span style="mso-spacerun: yes">&nbsp; </span>Feel free to drop me an email with the broad outline of what you are trying to achieve, and I&#8217;ll try to get you supported.<span style="mso-spacerun: yes">&nbsp; </span>That support might be something as lame as some suggestions from me on how I would tackle the problem.<span style="mso-spacerun: yes">&nbsp; </span>Or at the other extreme, I could imagine more formal support and conceivably some limited feature work.<span style="mso-spacerun: yes">&nbsp; </span>That other extreme really depends on how commercially significant your product is and on how well our business interests align.<span style="mso-spacerun: yes">&nbsp; </span>Obviously decisions like that are far outside my control, but I can at least hook you up with the right people if this seems like a sensible approach.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">Okay, one more &#8216;Finally&#8217;.<span style="mso-spacerun: yes">&nbsp; </span>From time to time readers of my blog send me emails asking if there are jobs available on the CLR team.<span style="mso-spacerun: yes">&nbsp; </span>At this moment, we do.<span style="mso-spacerun: yes">&nbsp; </span>Drop me an email if you are interested.<span style="mso-spacerun: yes">&nbsp; </span>It&#8217;s an extremely challenging team to work on, but the problems are truly fascinating.</p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p>&nbsp;</o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">
</font><img src="http://blogs.msdn.com/aggbug.aspx?PostID=77595" width="1" height="1"/><br />
<span style="font-size:8pt; font-style:italic">http://blogs.msdn.com/cbrumme/archive/2004/02/21/77595.aspx</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/24/hosting/feed/</wfw:commentRss>
	</item>
		<item>
		<title>When Are Two Algorithms the Same?</title>
		<link>http://cahtter.blogsome.com/2008/03/24/when-are-two-algorithms-the-same/</link>
		<comments>http://cahtter.blogsome.com/2008/03/24/when-are-two-algorithms-the-same/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 17:00:04 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/24/when-are-two-algorithms-the-same/</guid>
		<description><![CDATA[	When Are Two Algorithms the Same? Andreas Blass, Nachum Dershowitz, Yuri Gurevich. February 2008
	
People usually regard algorithms as more abstract than the programs that implement them. The natural way to formalize this idea is that algorithms are equivalence classes of programs with respect to a suitable equivalence relation. We argue that no such equivalence relation [...]]]></description>
			<content:encoded><![CDATA[	<p><small>When Are Two Algorithms the Same? Andreas Blass, Nachum Dershowitz, Yuri Gurevich. February 2008</small><br />
	<blockquote><p>
People usually regard algorithms as more abstract than the programs that implement them. The natural way to formalize this idea is that algorithms are equivalence classes of programs with respect to a suitable equivalence relation. We argue that no such equivalence relation exists.<br />
</blockquote></p>
	<p>
A bit more philosophical than usual, but the issue is quite relevant to discussions in the field.</p>
	<p>
It is possible to stipulate any equivalence relation that is considered useful (e.g., equivalence up to local transformations) but the notion of a universally applicable relation is indeed problematic.<br />
<span style="font-size:8pt; font-style:italic">http://lambda-the-ultimate.org/node/2729</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/24/when-are-two-algorithms-the-same/feed/</wfw:commentRss>
	</item>
		<item>
		<title>DevWeek 2008 Cross Platform Silverlight Demos</title>
		<link>http://cahtter.blogsome.com/2008/03/24/devweek-2008-cross-platform-silverlight-demos/</link>
		<comments>http://cahtter.blogsome.com/2008/03/24/devweek-2008-cross-platform-silverlight-demos/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 12:00:05 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/24/devweek-2008-cross-platform-silverlight-demos/</guid>
		<description><![CDATA[	I just finished the Cross Platform.NET on Silverlight talk at DevWeek. Demos can be downloaded from http://www.interact-sw.co.uk/downloads/DevWeek2008XPlatDemos.zip 
	
I&#8217;m all done at DevWeek for this year. But if you want to hear more about Silverlight, I&#8217;ll be teaching Pluralsight&#8217;s Applied Silverlight course in London later this month - running from 31st March. (And the following week [...]]]></description>
			<content:encoded><![CDATA[	<p>I just finished the Cross Platform.NET on Silverlight talk at DevWeek. Demos can be downloaded from http://www.interact-sw.co.uk/downloads/DevWeek2008XPlatDemos.zip </p>
	<p>
I&#8217;m all done at DevWeek for this year. But if you want to hear more about Silverlight, I&#8217;ll be teaching Pluralsight&#8217;s Applied Silverlight course in London later this month - running from 31st March. (And the following week I&#8217;ll be teaching our Applied WPF course, also in London.)
</p>
<br />
<span style="font-size:8pt; font-style:italic">http://www.interact-sw.co.uk/iangblog/2008/03/12/devweek-xplat-demos</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/24/devweek-2008-cross-platform-silverlight-demos/feed/</wfw:commentRss>
	</item>
		<item>
		<title>Turning bitboards from potential moves into legal moves, pawn moves, and conditional rules.</title>
		<link>http://cahtter.blogsome.com/2008/03/24/turning-bitboards-from-potential-moves-into-legal-moves-pawn-moves-and-conditional-rules/</link>
		<comments>http://cahtter.blogsome.com/2008/03/24/turning-bitboards-from-potential-moves-into-legal-moves-pawn-moves-and-conditional-rules/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 10:48:25 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/24/turning-bitboards-from-potential-moves-into-legal-moves-pawn-moves-and-conditional-rules/</guid>
		<description><![CDATA[	Also see: Generating WPF Content with LINQ
	The BitBoards so far have been astoundingly accurate at producing moves. But even after the moves have been produced they have to be fully validated. Take for instance, a bishop in the middle of the board. The number of potential moves for the bishop is 13 or so, but [...]]]></description>
			<content:encoded><![CDATA[	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p>The BitBoards so far have been astoundingly accurate at producing moves. But even after the moves have been produced they have to be fully validated. Take for instance, a bishop in the middle of the board. The number of potential moves for the bishop is 13 or so, but the number of valid moves, unless no spots are blocked, is much less. Further performing friendly versus non-friendly extension is extremely importan since you can&#8217;t move into a friendly position, but you can move into the first occuring non-friendly position (capturing). I&#8217;ve found some interesting transformations here, but once I can more fully validate them I&#8217;ll start to post their intricacies.</p>
	<p>Even more frustrating are the pawns. Pawns are capable of special feats when in their original file (forward by 2), they are allowed capturing moves that are different from their standard movement rules, and they are also allowed the ability to capture en-passant. Deciding where and how to implement these extra conditions is very important. Remember the original blocking square algorithm I implemented for removing invalid moves consisted of:</p>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"></blockquote>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"><p>uint myPieces =&#8230;; uint notMine = ~myPieces; uint validMoves = moves &amp; notMine;</p></blockquote>
	<p dir="ltr">This has to be expanded a bit, since notMine actually points to all empty and enemy squares. What we need now is a blocking region for all enemy squares (which we have to store anyway, since eventually the board swaps sides and enemy and friendly are reversed). The valid moves become something like:</p>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"></blockquote>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"><p> <a id="more-23"></a><br />
<p dir="ltr">uint nonCapture = pawnNonCapture[x]; uint capture = pawnCapture[x];<br />uint&nbsp;validNonCapture = (~(myPieces &amp; enemyPieces) &amp; nonCapture);<br />uint validCapture = capture &amp; enemyPieces;<br />if ( board.enPassant ) { /* special case when prior moves allow */ }<br />uint validMoves = validNonCapture | validCapture;</p></blockquote>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://devsoft.blogsome.com/2008/03/23/transparentproxy-2/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/reporting-services-administration-changes-in-katmai-vnext/"  title="Reporting Services administration changes in Katmai (v.Next)">Reporting Services administration changes in Katmai (v.Next)</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p dir="ltr">Even with all of this magical bit-shifting we aren&#8217;t accounting for visibility off the first rank. After all, if we are blocked forward 1 and not forward 2, this might still give that as a valid move. After all of this work on pawn movements, it might be better just to leave them to special cased code because of their intricacies compared to other pieces. What can we do then to quickly generate pawn moves? Some ideas are floating around for sure. If I have a BitBoard of all my pawns I can easily do the following:</p>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"></blockquote>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"><p dir="ltr">uint validMoves = (curPawns&nbsp;&lt;&lt; <img src='http://cahtter.blogsome.com/wp-images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' />  &amp; (~(myPieces &amp; enemyPieces)); // one sided, but basically advance and check.<br />validMoves |= ((validMoves &amp; 0xFF0000) &lt;&lt; <img src='http://cahtter.blogsome.com/wp-images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' />  &amp; (~(myPieces &amp; enemyPieces)); // all that were able to move forward 1, move 2</p></blockquote>
	<p dir="ltr">Some of the above information would be pregenerated, but you can see all of the gruesome details in action. Captures are a basic extension of the above. The basic premise involves 7 or 9 bit shifting operations along with clearing of the overflow file. What do I mean by overflow file? Well, take the rightmost file, h, and then tell me how a pawn would attack off the right side of the board. If we shift by 9 still the pawn in file h, would wrap around and attack the other side of the board. Clearing the pawns in the oveflow ranks is the only way I can think of getting rid of this for now.</p>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"></blockquote>
	<blockquote dir="ltr" style="MARGIN-RIGHT: 0px"><div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Help Server">Live Help Server</a>: Jerry Messenger Server is Live Chat with Users on your websites.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/rest2sql-in-a-jiffy-with-tagspace-for-spice/"  title="REST2SQL in a Jiffy, with Tagspace for Spice">REST2SQL in a Jiffy, with Tagspace for Spice</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/reporting-services-administration-changes-in-katmai-vnext/"  title="Reporting Services administration changes in Katmai (v.Next)">Reporting Services administration changes in Katmai (v.Next)</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://devsoft.blogsome.com/2008/03/22/big-in-japan-2/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://devsoft.blogsome.com/2008/03/23/prototypes-and-java-config-with-spring-2/"  title="Prototypes and Java Config with Spring">Prototypes and Java Config with Spring</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/23/yes-it-does-mean-everything/"  title="Yes, it does mean everything">Yes, it does mean everything</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/22/win-friends-and-influence-your-team/"  title="Win friends and influence your team">Win friends and influence your team</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/single-source-code-base-for-silverlight-and-wpf-solutions/"  title="Single source code base for Silverlight and WPF solutions">Single source code base for Silverlight and WPF solutions</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://devsoft.blogsome.com/2008/03/22/c-30-lambdas-and-type-inference/"  title="C# 3.0 Lambdas and Type Inference">C# 3.0 Lambdas and Type Inference</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://devsoft.blogsome.com/2008/03/23/transparentproxy-2/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/quaker-votes/"  title="Quaker votes">Quaker votes</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/doing-the-deal-and-dishing-the-dirt/"  title="Doing the Deal and Dishing the Dirt">Doing the Deal and Dishing the Dirt</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfroms-second-bind/"  title="LoadFrom's Second Bind">LoadFrom&#8217;s Second Bind</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://devsoft.blogsome.com/2008/03/22/never-keep-your-emotions-bottled-up-2/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/21/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://devsoft.blogsome.com/2008/03/23/prototypes-and-java-config-with-spring-2/"  title="Prototypes and Java Config with Spring">Prototypes and Java Config with Spring</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/05/hello-world/"  title="Hello world!">Hello world!</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/bloggers-in-the-mavs-locker-room/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/bloggers-in-the-mavs-locker-room/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/21/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/devweek-2008-cross-platform-silverlight-demos/"  title="DevWeek 2008 Cross Platform Silverlight Demos">DevWeek 2008 Cross Platform Silverlight Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/21/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/bloggers-in-the-mavs-locker-room/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/doing-the-deal-and-dishing-the-dirt/"  title="Doing the Deal and Dishing the Dirt">Doing the Deal and Dishing the Dirt</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/compatability/"  title="Compatability">Compatability</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/22/win-friends-and-influence-your-team/"  title="Win friends and influence your team">Win friends and influence your team</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://kerrysoft16.edublogs.org/2008/03/22/publishing-good-reviews-bad-reviews-and-hurting-oooh-so-many-feelings/"  title="Publishing: Good reviews, bad reviews, and hurting oooh so many feelings.">Publishing: Good reviews, bad reviews, and hurting oooh so many feelings.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/quaker-votes/"  title="Quaker votes">Quaker votes</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p dir="ltr">uint validCaptures = ((curPawns &amp; clearRank[0]) &lt;&lt; 7) &amp; enemyPieces;<br />validCaptures |= ((curPawns &amp; clearRank[7]) &lt;&lt; 9) &amp; enemyPieces;</p></blockquote>
	<p dir="ltr">It is fairly nice to be able to calculate all pawn moves simultaneously in this manner. I&#8217;d still calculate en-passant separately because it has side-effects. The attacking square is different from the square where the enemies piece would be removed. It is an extra piece of information that the board has to carry around to make sure that it always performs the appropriate captures.</p>
	<p>If you have questions about some of the rules, I actually found the following a bit helpful. I have a chess rules book that I tend to go to first for explanation, especially since I need to ensure accuracy in the engine. When I don&#8217;t feel like leafing I&#8217;ll check something out here in the FAQ and then put a little comment in the code to go back later and check the official rules http://www.chessvariants.org/d.chess/faq.html. Even if you know how to play chess, these FAQs can be algorist playgrounds, since often overlooked newbie questions can point out subtleties, patterns and optimizations you might not otherwise dream-up.</p>
<img src="http://weblogs.asp.net/aggbug.aspx?PostID=246983" width="1" height="1"/><br />
<span style="font-size:8pt; font-style:italic">http://weblogs.asp.net/justin_rogers/archive/2004/10/24/246983.aspx</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/24/turning-bitboards-from-potential-moves-into-legal-moves-pawn-moves-and-conditional-rules/feed/</wfw:commentRss>
	</item>
		<item>
		<title>The Exception Model</title>
		<link>http://cahtter.blogsome.com/2008/03/24/the-exception-model/</link>
		<comments>http://cahtter.blogsome.com/2008/03/24/the-exception-model/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 10:48:16 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
	<category>Software</category>
		<guid>http://cahtter.blogsome.com/2008/03/24/the-exception-model/</guid>
		<description><![CDATA[	Also see: Spring Web Flow features and feedback request
	I had
hoped this article would be on changes to the next version of the CLR which
allow it to be hosted inside SQL Server and other “challenging”
environments.&nbsp; This is more
generally interesting than you might think, because it creates an opportunity
for other processes (i.e. your
processes) to host the CLR [...]]]></description>
			<content:encoded><![CDATA[	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/spring-web-flow-features-and-feedback-request/"  title="Spring Web Flow features and feedback request">Spring Web Flow features and feedback request</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I had<br />
hoped this article would be on changes to the next version of the CLR which<br />
allow it to be hosted inside SQL Server and other “challenging”<br />
environments.<span style="mso-spacerun: yes">&nbsp; </span>This is more<br />
generally interesting than you might think, because it creates an opportunity<br />
for other processes (i.e. <i style="mso-bidi-font-style: normal">your</i><br />
processes) to host the CLR with a similar level of integration and control.<span style="mso-spacerun: yes">&nbsp; </span>This includes control over memory usage,<br />
synchronization, threading (including fibers), extended security models,<br />
assembly storage, and more.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt">< ?xml:namespace prefix = o ns =<br />
"urn:schemas-microsoft-com:office:office" /><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>However,<br />
that topic is necessarily related to our next release, and I cannot talk about<br />
deep details of that next release until those details have been publicly<br />
disclosed.<span style="mso-spacerun: yes">&nbsp; </span>In late October,<br />
Microsoft is holding its PDC and I expect us to disclose many details at that<br />
time.<span style="mso-spacerun: yes">&nbsp; </span>In fact, I’m signed up to be<br />
a member of a PDC panel on this topic.<span style="mso-spacerun: yes">&nbsp;<br />
</span>If you work on a database or an application server or a similarly<br />
complicated product that might benefit from hosting the CLR, you may want to<br />
attend.</font></p>
	<p><a id="more-22"></a><br />
<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/exception-handling-in-running-a-business/"  title="Exception Handling in Running a Business">Exception Handling in Running a Business</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/loadfile-vs-loadfrom/"  title="LoadFile vs. LoadFrom">LoadFile vs. LoadFrom</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/spring-web-flow-features-and-feedback-request/"  title="Spring Web Flow features and feedback request">Spring Web Flow features and feedback request</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/the-internet-is-officially-dead-boring-its-the-economy-stupid/"  title="The Internet is Officially Dead &amp; Boring - Its the economy stupid !">The Internet is Officially Dead &amp; Boring - Its the economy stupid !</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/java-design-operator-overloading-and-people/"  title="Java design, operator overloading and people">Java design, operator overloading and people</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/devweek-2008-cross-platform-silverlight-demos/"  title="DevWeek 2008 Cross Platform Silverlight Demos">DevWeek 2008 Cross Platform Silverlight Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/memory-model/"  title="Memory Model">Memory Model</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/access-to-old-blogs/"  title="Access to old blogs">Access to old blogs</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/silverlight-2-beta-1-cross-domain-bug/"  title="Silverlight 2 Beta 1 Cross Domain Bug">Silverlight 2 Beta 1 Cross Domain Bug</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/big-in-japan/"  title="Big in Japan">Big in Japan</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/the-internet-is-officially-dead-boring-its-the-economy-stupid/"  title="The Internet is Officially Dead &amp; Boring - Its the economy stupid !">The Internet is Officially Dead &amp; Boring - Its the economy stupid !</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/doing-the-deal-and-dishing-the-dirt/"  title="Doing the Deal and Dishing the Dirt">Doing the Deal and Dishing the Dirt</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/tagspace-meet-claimspace/"  title="Tagspace, Meet Claimspace">Tagspace, Meet Claimspace</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/ive-finally-settled-into-my-new-position-on-the-internet-explorer-team/"  title="I've finally settled into my new position on the Internet Explorer team...">I&#8217;ve finally settled into my new position on the Internet Explorer team&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/linq-the-uber-findcontrol/"  title="LINQ - The Uber FindControl">LINQ - The Uber FindControl</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>After<br />
we’ve disclosed the hosting changes for our next release, you can expect a blog<br />
on hosting in late October or some time in November.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Instead,<br />
this blog is on the managed exception model.<span style="mso-spacerun: yes">&nbsp; </span>This is an unusual topic for me.<span style="mso-spacerun: yes">&nbsp; </span>In the past, I’ve picked topics where I<br />
can dump information without having to check any of my facts or do any<br />
research.<span style="mso-spacerun: yes">&nbsp; </span>But in the case of<br />
exceptions I keep finding questions I cannot answer.<span style="mso-spacerun: yes">&nbsp; </span>At the top level, the managed exception<br />
model is nice and simple.<span style="mso-spacerun: yes">&nbsp; </span>But – as<br />
with everything else in software – the closer you look, the more you<br />
discover.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So for<br />
the first time I decided to have some CLR experts read my blog entry before I<br />
post it.<span style="mso-spacerun: yes">&nbsp; </span>In addition to pointing<br />
out a bunch of my errors, all the reviewers were unanimous on one point: I<br />
should write shorter blogs.</font></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Custom Software Solutions">Custom Software Solutions</a>. Billing and Invoicing Solutions, eCommerce and Website design.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/bloggers-in-the-mavs-locker-room/"  title="Bloggers in the Mavs Locker Room ?">Bloggers in the Mavs Locker Room ?</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/24/brad-abrams-pixel8-interview-podcast-posted/"  title="Brad Abrams' pixel8 Interview Podcast posted">Brad Abrams&#8217; pixel8 Interview Podcast posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/aspnet-mvc-in-codeplex-and-extensible-unit-testing/"  title="ASP.NET MVC in CodePlex and Extensible Unit Testing">ASP.NET MVC in CodePlex and Extensible Unit Testing</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/reporting-services-administration-changes-in-katmai-vnext/"  title="Reporting Services administration changes in Katmai (v.Next)">Reporting Services administration changes in Katmai (v.Next)</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/05/hello-world/"  title="Hello world!">Hello world!</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/spring-web-flow-features-and-feedback-request/"  title="Spring Web Flow features and feedback request">Spring Web Flow features and feedback request</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of<br />
course, we can’t talk about managed exceptions without first considering Windows<br />
Structured Exception Handling (SEH).<span style="mso-spacerun: yes">&nbsp;<br />
</span>And we also need to look at the C++ exception model.<span style="mso-spacerun: yes">&nbsp; </span>That’s because both managed exceptions<br />
and C++ exceptions are implemented on top of the underlying SEH mechanism, and<br />
because managed exceptions must interoperate with both SEH and C++<br />
exceptions.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>Windows<br />
SEH<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Since<br />
it’s at the base of all exception handling on Windows, let’s look at SEH<br />
first.<span style="mso-spacerun: yes">&nbsp; </span>As far as I know, the<br />
definitive explanation of SEH is still Matt Pietrek’s excellent 1997 article for<br />
Microsoft Systems Journal: </font>http://www.microsoft.com/msj/0197/exception/exception.aspx <font face=Tahoma size=2>.<span style="mso-spacerun: yes">&nbsp; </span>There have<br />
been some extensions since then, like vectored exception handlers, some security<br />
enhancements, and the new mechanisms to support IA64 and AMD64.<span style="mso-spacerun: yes">&nbsp; </span>(It’s hard to base exceptions on FS:[0]<br />
chains if your processor doesn’t have an FS segment register).<span style="mso-spacerun: yes">&nbsp; </span>We’ll look at all these changes<br />
shortly.<span style="mso-spacerun: yes">&nbsp; </span>But Matt’s 1997 article<br />
remains a goldmine of information.<span style="mso-spacerun: yes">&nbsp;<br />
</span>In fact, it was very useful to the developers who implemented exceptions<br />
in the CLR.</font></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Custom Software Development">Custom Software</a> Development for Real-Estate, Hosting providers, Workflow and Business Management Systems.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/c-30-lambdas-and-type-inference/"  title="C# 3.0 Lambdas and Type Inference">C# 3.0 Lambdas and Type Inference</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The SEH<br />
model is exposed by MSVC via two constructs:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<ol style="MARGIN-TOP: 0in" type=1>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l0 level1 lfo1"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>__try {…}<br />
 __except(filter_expression) {…}<o :p></o></font></span></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l0 level1 lfo1"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>__try {…} __finally<br />
 {…}<o :p></o></font></span></li>
</ol>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Matt’s<br />
article explains how the underlying mechanism of two passes over a chain of<br />
single callbacks is used to provide try/except/finally semantics.<span style="mso-spacerun: yes">&nbsp; </span>Briefly, the OS dispatches an exception<br />
by retrieving the head of the SEH chain from TLS.<span style="mso-spacerun: yes">&nbsp; </span>Since the head of this chain is at the<br />
top of the TIB/TEB (Thread Information Block / Thread Environment Block,<br />
depending on the OS and the header file you look at), and since the FS segment<br />
register provides fast access to this TLS block on X86, the SEH chain is often<br />
called the FS:[0] chain.</font></p>
	<div class="interline"><a href="http://www.multisoftgroup.com/" title="Softwre Development">Softwre Development</a> for small and middle size companies. World-class software applications.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/devweek-2008-cross-platform-silverlight-demos/"  title="DevWeek 2008 Cross Platform Silverlight Demos">DevWeek 2008 Cross Platform Silverlight Demos</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/transparentproxy/"  title="TransparentProxy">TransparentProxy</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/silverlight-2-beta-1-cross-domain-bug/"  title="Silverlight 2 Beta 1 Cross Domain Bug">Silverlight 2 Beta 1 Cross Domain Bug</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/c-30-lambdas-and-type-inference/"  title="C# 3.0 Lambdas and Type Inference">C# 3.0 Lambdas and Type Inference</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/doing-the-deal-and-dishing-the-dirt/"  title="Doing the Deal and Dishing the Dirt">Doing the Deal and Dishing the Dirt</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/the-internet-is-officially-dead-boring-its-the-economy-stupid/"  title="The Internet is Officially Dead &amp; Boring - Its the economy stupid !">The Internet is Officially Dead &amp; Boring - Its the economy stupid !</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/23/never-keep-your-emotions-bottled-up/"  title="Never keep your emotions bottled up">Never keep your emotions bottled up</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Each<br />
entry consists of a next or a prev pointer (depending on how you look at it) and<br />
a callback function.<span style="mso-spacerun: yes">&nbsp; </span>You can add<br />
whatever data you like after that standard entry header.<span style="mso-spacerun: yes">&nbsp; </span>The callback function is called with all<br />
sorts of additional information related to the exception that’s being<br />
processed.<span style="mso-spacerun: yes">&nbsp; </span>This includes the<br />
exception record and the register state of the machine which was captured at the<br />
time of the exception.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>To<br />
implement the 1<sup>st</sup> form of MSVC SEH above (__try/__except), the<br />
callback evaluates the filter expression during the first pass over the handler<br />
chain.<span style="mso-spacerun: yes">&nbsp; </span>As exposed by MSVC, the<br />
filter expression can result in one of three legal values:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>EXCEPTION_CONTINUE_EXECUTION<br />
= -1<o :p></o></font></span></p>
	<div class="interline"><a href="http://www.j-livesupport.com/affiliate/pages/117.php" title="Live Person Software">Live Person Software</a>: Turn website visitors into your customers.
</div>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/single-source-code-base-for-silverlight-and-wpf-solutions/"  title="Single source code base for Silverlight and WPF solutions">Single source code base for Silverlight and WPF solutions</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/exception-handling-in-running-a-business/"  title="Exception Handling in Running a Business">Exception Handling in Running a Business</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/a-web-site-is-not-an-rss-feednor-the-reverse/"  title="A web site is not an RSS feed...nor the reverse.">A web site is not an RSS feed&#8230;nor the reverse.</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/aspnet-mvc-in-codeplex-and-extensible-unit-testing/"  title="ASP.NET MVC in CodePlex and Extensible Unit Testing">ASP.NET MVC in CodePlex and Extensible Unit Testing</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/24/compatability/"  title="Compatability">Compatability</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/generating-wpf-content-with-linq/"  title="Generating WPF Content with LINQ">Generating WPF Content with LINQ</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/23/reporting-services-administration-changes-in-katmai-vnext/"  title="Reporting Services administration changes in Katmai (v.Next)">Reporting Services administration changes in Katmai (v.Next)</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/21/cool-silverlight-momentum-video-posted/"  title="Cool Silverlight Momentum Video Posted">Cool Silverlight Momentum Video Posted</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://jimmy69.wordpress.com/2008/03/22/dare-obasanjo-on-c-anonymous-types/"  title="Dare Obasanjo on C# Anonymous Types">Dare Obasanjo on C# Anonymous Types</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/resizing-a-form-has-always-been-a-pain-in-the-rectum/"  title="Resizing a Form has always been a pain in the rectum...">Resizing a Form has always been a pain in the rectum&#8230;</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/21/exception-handling-in-running-a-business/"  title="Exception Handling in Running a Business">Exception Handling in Running a Business</a></i></p>
	<p style="line-height: 150%"><i>Also see: <a href="http://chatter66.rticlz.com/2008/03/22/aspnet-mvc-in-codeplex-and-extensible-unit-testing/"  title="ASP.NET MVC in CodePlex and Extensible Unit Testing">ASP.NET MVC in CodePlex and Extensible Unit Testing</a></i></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>EXCEPTION_CONTINUE_SEARCH =<br />
false 0<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>EXCEPTION_EXECUTE_HANDLER =<br />
true 1<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of<br />
course, the filter could also throw its own exception.<span style="mso-spacerun: yes">&nbsp; </span>That’s not generally desirable, and I’ll<br />
discuss that possibility and other flow control issues later.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But if<br />
you look at the underlying SEH mechanism, the handler actually returns an<br />
EXCEPTION_DISPOSITION:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>typedef enum<br />
_EXCEPTION_DISPOSITION<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>{<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;<br />
</span>ExceptionContinueExecution,<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;<br />
</span>ExceptionContinueSearch,<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;<br />
</span>ExceptionNestedException,<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;<br />
</span>ExceptionCollidedUnwind<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>}<br />
EXCEPTION_DISPOSITION;<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So<br />
there’s some mapping that MSVC is performing here.<span style="mso-spacerun: yes">&nbsp; </span>Part of that mapping is just a trivial<br />
conversion between the MSVC filter values and the SEH handler values.<span style="mso-spacerun: yes">&nbsp; </span>For instance ExceptionContinueSearch has<br />
the value 1 at the SEH handler level but the equivalent<br />
EXCEPTION_CONTINUE_SEARCH has the value 0 at the MSVC filter level.<span style="mso-spacerun: yes">&nbsp; </span>Ouch.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But the<br />
other part of the mapping has to do with a difference in functionality.<span style="mso-spacerun: yes">&nbsp; </span>For example, ExceptionNestedException<br />
and ExceptionCollidedUnwind are primarily used by the OS dispatch mechanism<br />
itself.<span style="mso-spacerun: yes">&nbsp; </span>We’ll see the circumstances<br />
in which they arise later.<span style="mso-spacerun: yes">&nbsp; </span>More<br />
importantly, MSVC filters can indicate that the __except clause should run by<br />
returning EXCEPTION_EXECUTE_HANDLER.<span style="mso-spacerun: yes">&nbsp;<br />
</span>But we shall see that at the SEH level this decision is achieved by<br />
having the exception dispatch routine fix up the register context and then<br />
resuming execution at the right spot.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
EXCEPTION_CONTINUE_EXECUTION case supports a rather esoteric use of SEH.<span style="mso-spacerun: yes">&nbsp; </span>This return value allows the filter to<br />
correct the problem that caused the exception and to resume execution at the<br />
faulting instruction.<span style="mso-spacerun: yes">&nbsp; </span>For example,<br />
an application might be watching to see when segments are being written to so<br />
that it can log this information.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This could be achieved by marking the segment as ReadOnly and waiting for<br />
an exception to occur on first write.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Then the filter could use VirtualProtect to change the segment containing<br />
the faulting address to ReadWrite and then restart the faulting<br />
instruction.<span style="mso-spacerun: yes">&nbsp; </span>Alternatively, the<br />
application could have two VirtualAllocs for each region of memory.<span style="mso-spacerun: yes">&nbsp; </span>One of these could be marked as ReadOnly<br />
and the second could be a shadow that is marked as ReadWrite.<span style="mso-spacerun: yes">&nbsp; </span>Now the exception filter can simply<br />
change the register state of the CPU that faulted, so that the register<br />
containing the faulting address is changed from the ReadOnly segment to the<br />
shadowed ReadWrite segment.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Obviously anyone who is playing these games must have a lot of<br />
sophistication and a deep knowledge of how the program executes.<span style="mso-spacerun: yes">&nbsp; </span>Some of these games work better if you<br />
can constrain the code that’s generated by your program to only touch faulting<br />
memory using a predictable cliché like offsets from a particular<br />
register.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’ll<br />
talk about this kind of restartable or resumable exception in the context of<br />
managed code later.<span style="mso-spacerun: yes">&nbsp; </span>For now, let’s<br />
pretend that the filter either returns “true – I would like my ‘except’ clause<br />
to handle this exception” or “false – my ‘except’ clause is uninterested in this<br />
exception”.<span style="mso-spacerun: yes">&nbsp; </span>If the filter returns<br />
false, the next SEH handler is fetched from the chain and it is asked this same<br />
question.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The OS<br />
is pretty paranoid about corrupt stacks during this chain traversal.<span style="mso-spacerun: yes">&nbsp; </span>It checks that all chain entries are<br />
within the bounds of the stack.<span style="mso-spacerun: yes">&nbsp;<br />
</span>(These bounds are also recorded in the TEB).<span style="mso-spacerun: yes">&nbsp; </span>The OS also checks that all entries are<br />
in ascending order on the stack.<span style="mso-spacerun: yes">&nbsp; </span>If<br />
you violate these rules, the OS will consider the stack to be corrupt and will<br />
be unable to process exceptions.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This is one of the reasons that a Win32 application cannot break its<br />
stack into multiple disjoint segments as an innovative technique for dealing<br />
with stack overflow.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway,<br />
eventually a handler says “true – I would like my ‘except’ clause to handle this<br />
exception”.<span style="mso-spacerun: yes">&nbsp; </span>That’s because there’s<br />
a backstop entry at the end of the chain which is placed there by the OS when<br />
the thread is created.<span style="mso-spacerun: yes">&nbsp; </span>This last<br />
entry wants to handle all the exceptions, even if your application-level<br />
handlers never do.<span style="mso-spacerun: yes">&nbsp; </span>That’s where you<br />
get the default OS behavior of consulting the unhandled exception filter list,<br />
throwing up dialog boxes for Terminate or Debug, etc.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>As soon<br />
as a filter indicates that it wants to handle an exception, the first pass of<br />
exception handling finishes and the second pass begins.<span style="mso-spacerun: yes">&nbsp; </span>As Matt’s article explains, the handler<br />
can use the poorly documented RtlUnwind service to deliver second pass<br />
notifications to all the previous handlers and pop them off the handler<br />
chain.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In other<br />
words, no unwinding happened as the first pass progressed.<span style="mso-spacerun: yes">&nbsp; </span>But during the second pass we see two<br />
distinct forms of unwind.<span style="mso-spacerun: yes">&nbsp; </span>The first<br />
form involves popping SEH records from the chain that was threaded from<br />
TLS.<span style="mso-spacerun: yes">&nbsp; </span>Each such SEH record is popped<br />
before the corresponding handler gets called for the second pass.<span style="mso-spacerun: yes">&nbsp; </span>This leaves the SEH chain in a<br />
reasonable form for any nested exceptions that might occur within a<br />
handler.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
other form of unwind is the actual popping of the CPU stack.<span style="mso-spacerun: yes">&nbsp; </span>This doesn’t happen as eagerly as the<br />
popping of the SEH records.<span style="mso-spacerun: yes">&nbsp; </span>On X86,<br />
EBP is used as the frame pointer for methods containing SEH.<span style="mso-spacerun: yes">&nbsp; </span>ESP points to the top of the stack, as<br />
always.<span style="mso-spacerun: yes">&nbsp; </span>Until the stack is actually<br />
unwound, all the handlers are executed on top of the faulting exception<br />
frame.<span style="mso-spacerun: yes">&nbsp; </span>So the stack actually grows<br />
when a handler is called for the first or second pass.<span style="mso-spacerun: yes">&nbsp; </span>EBP is set to the frame of the method<br />
containing a filter or finally clause so that local variables of that method<br />
will be in scope.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
actual popping of the stack doesn’t occur until the catching ‘except’ clause is<br />
executed.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So we’ve<br />
got a handler whose filter announced in the first pass that it would handle this<br />
exception via EXCEPTION_EXECUTE_HANDLER.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And that handler has driven the second pass by unwinding and delivering<br />
all the second pass notifications.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Typically it will then fiddle with the register state in the exception<br />
context and resume execution at the top of the appropriate ‘except’ clause.<span style="mso-spacerun: yes">&nbsp; </span>This isn’t necessarily the case, and<br />
later we’ll see some situations where the exception propagation gets<br />
diverted.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>How<br />
about the try/finally form of SEH?<span style="mso-spacerun: yes">&nbsp;<br />
</span>Well, it’s built on the same underlying notion of a chain of<br />
callbacks.<span style="mso-spacerun: yes">&nbsp; </span>During the first pass<br />
(the one where the filters execute, to decide which except block is going to<br />
catch), the finally handlers all say EXCEPTION_CONTINUE_SEARCH.<span style="mso-spacerun: yes">&nbsp; </span>They never actually catch anything.<span style="mso-spacerun: yes">&nbsp; </span>Then in the second pass, they execute<br />
their finally blocks.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>Subsequent<br />
additions to SEH<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>All of<br />
the above – and a lot more – is in Matt’s article.<span style="mso-spacerun: yes">&nbsp; </span>There are a few things that aren’t in<br />
his article because they were added to the model later.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>For<br />
example, Windows XP introduced the notion of a vectored exception handler.<span style="mso-spacerun: yes">&nbsp; </span>This allows the application to register<br />
for a first crack at an exception, without having to wait for exception handling<br />
to propagate down the stack to an embedded handler.<span style="mso-spacerun: yes">&nbsp; </span>Fortunately, Matt wrote an “Under The<br />
Hood” article on this particular topic.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This can be found at </font>http://msdn.microsoft.com/msdnmag/issues/01/09/hood/default.aspx <font face=Tahoma size=2>.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Another<br />
change to SEH is related to security.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Buffer overruns – whether on the stack or in heap blocks – remain a<br />
favorite attack vector for hackers.<span style="mso-spacerun: yes">&nbsp;<br />
</span>A typical buffer overrun attack is to pass a large string as an argument<br />
to an API.<span style="mso-spacerun: yes">&nbsp; </span>If that API expected a<br />
shorter string, it might have a local on the stack like “char<br />
filename[256];”.<span style="mso-spacerun: yes">&nbsp; </span>Now if the API is<br />
foolish enough to strcpy a malicious hacker’s argument into that buffer, then<br />
the hacker can put some fairly arbitrary data onto the stack at addresses higher<br />
(further back on the stack) than that ‘filename’ buffer.<span style="mso-spacerun: yes">&nbsp; </span>If those higher locations are supposed<br />
to contain call return addresses, the hacker may be able to get the CPU to<br />
transfer execution into the buffer itself.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Oops.<span style="mso-spacerun: yes">&nbsp; </span>The hacker is<br />
injecting arbitrary code and then executing it, potentially inside someone<br />
else’s process or under their security credentials.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There’s<br />
a new speed bump that an application can use to reduce the likelihood of a<br />
successful stack-based buffer overrun attack.<span style="mso-spacerun: yes">&nbsp; </span>This involves the /GS C++ compiler<br />
switch, which uses a cookie check in the function epilog to determine whether a<br />
buffer overrun has corrupted the return address before executing a return based<br />
on its value.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>However,<br />
the return address trick is only one way to exploit buffer overruns.<span style="mso-spacerun: yes">&nbsp; </span>We’ve already seen that SEH records are<br />
necessarily built on the stack.<span style="mso-spacerun: yes">&nbsp; </span>And<br />
in fact the OS actually checks to be sure they are within the stack bounds.<span style="mso-spacerun: yes">&nbsp; </span>Those SEH records contain callback<br />
pointers which the OS will invoke if an exception occurs.<span style="mso-spacerun: yes">&nbsp; </span>So another way to exploit a buffer<br />
overrun is to rewrite the callback pointer in an SEH record on the stack.<span style="mso-spacerun: yes">&nbsp; </span>There’s a new linker switch (/SAFESEH)<br />
that can provide its own speed bump against this sort of attack.<span style="mso-spacerun: yes">&nbsp; </span>Modules built this way declare that all<br />
their handlers are embedded in a table in the image; they do not point to<br />
arbitrary code sequences sprinkled in the stack or in heap blocks.<span style="mso-spacerun: yes">&nbsp; </span>During exception processing, the<br />
exception callbacks can be validated against this table.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of<br />
course, the first and best line of defense against all these attacks is to never<br />
overrun a buffer.<span style="mso-spacerun: yes">&nbsp; </span>If you are<br />
writing in managed code, this is usually pretty easy.<span style="mso-spacerun: yes">&nbsp; </span>You cannot create a buffer overrun in<br />
managed code unless the CLR contains a bug or you perform unsafe operations<br />
(e.g. unverifiable MC++ or ‘unsafe’ in C#) or you use high-privilege unsafe APIs<br />
like StructureToPtr or the various overloads of Copy in the<br />
System.Runtime.InteropServices.Marshal class.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So, not<br />
surprisingly and not just for this reason, I recommend writing in managed<br />
code.<span style="mso-spacerun: yes">&nbsp; </span>But if you must write some<br />
unmanaged code, you should seriously consider using a String abstraction that<br />
eliminates all those by-rote opportunities for error.<span style="mso-spacerun: yes">&nbsp; </span>And if you must code each strcpy<br />
individually, be sure to use strncpy instead!</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>A final<br />
interesting change to the OS SEH model since Matt’s article is due to<br />
Win64.<span style="mso-spacerun: yes">&nbsp; </span>Both IA64 and AMD64 have a<br />
model for exception handling that avoids reliance on an explicit handler chain<br />
that starts in TLS and is threaded through the stack.<span style="mso-spacerun: yes">&nbsp; </span>Instead, exception handling relies on<br />
the fact that on 64-bit systems we can perfectly unwind a stack.<span style="mso-spacerun: yes">&nbsp; </span>And this ability is itself due to the<br />
fact that these chips are severely constrained on the calling conventions they<br />
support.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you<br />
look at X86, there are an unbounded number of calling conventions possible.<span style="mso-spacerun: yes">&nbsp; </span>Sure, there are a few common well-known<br />
conventions like stdcall, cdecl, thiscall and fastcall.<span style="mso-spacerun: yes">&nbsp; </span>But optimizing compilers can invent<br />
custom calling conventions based on inter-procedural analysis.<span style="mso-spacerun: yes">&nbsp; </span>And developers writing in assembly<br />
language can make novel decisions about which registers to preserve vs. scratch,<br />
how to use the floating point stack, how to encode structs into registers,<br />
whether to back-propagate results by re-using the stack that contained in-bound<br />
arguments, etc.<span style="mso-spacerun: yes">&nbsp; </span>Within the CLR, we<br />
have places where we even unbalance the stack by encoding data after a CALL<br />
instruction, which is then addressable via the return address.<span style="mso-spacerun: yes">&nbsp; </span>This is a particularly dangerous game<br />
because it upsets the branch prediction code of the CPU and can cause prediction<br />
misses on several subsequent RET instructions.<span style="mso-spacerun: yes">&nbsp; </span>So we are careful to reserve this<br />
technique for low frequency call paths.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And we also have some stubs that compute indirect JMPs to out-of-line RET<br />
‘n’ instructions in order to rebalance the stack.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>It would<br />
be impossible for a stack crawler to successfully unwind these bizarre stacks<br />
for exception purposes, without completely simulating arbitrary code<br />
execution.<span style="mso-spacerun: yes">&nbsp; </span>So on X86 the exception<br />
mechanism must rely on the existence of a chain of crawlable FS:[0] handlers<br />
that is explicitly maintained.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Incidentally, the above distinction between perfect stack crawling on<br />
64-bit systems vs. hopeless stack crawling on X86 systems has deeper<br />
repercussions for the CLR than just exception handling.<span style="mso-spacerun: yes">&nbsp; </span>The CLR needs the ability to crawl all<br />
the managed portions of a thread’s stack on all architectures.<span style="mso-spacerun: yes">&nbsp; </span>This is a requirement for proper<br />
enforcement of Code Access Security; for accurate reporting of managed<br />
references to the GC; for hijacking return addresses in order to asynchronously<br />
take control of threads; and for various other reasons.<span style="mso-spacerun: yes">&nbsp; </span>On X86, the CLR devotes considerable<br />
resources to achieving this.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway,<br />
on 64-bit systems the correspondence between an activation record on the stack<br />
and the exception record that applies to it is not achieved through an FS:[0]<br />
chain.<span style="mso-spacerun: yes">&nbsp; </span>Instead, unwinding of the<br />
stack reveals the code addresses that correspond to a particular activation<br />
record.<span style="mso-spacerun: yes">&nbsp; </span>These instruction pointers<br />
of the method are looked up in a table to find out whether there are any<br />
__try/__except/__finally clauses that cover these code addresses.<span style="mso-spacerun: yes">&nbsp; </span>This table also indicates how to proceed<br />
with the unwind by describing the actions of the method epilog.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>Managed<br />
Exceptions<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Okay,<br />
enough about SEH – for now.<span style="mso-spacerun: yes">&nbsp; </span>Let’s<br />
switch to the managed exception model.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This model contains a number of constructs.<span style="mso-spacerun: yes">&nbsp; </span>Depending on the language you code in,<br />
you probably only have access to a subset of these.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} finally<br />
{…}<o :p></o></font></span></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
pretty standard.<span style="mso-spacerun: yes">&nbsp; </span>All managed<br />
languages should expose this, and it should be the most common style of<br />
exception handling in user code.<span style="mso-spacerun: yes">&nbsp; </span>Of<br />
course, in the case of MC++ the semantics of ‘finally’ is exposed through<br />
auto-destructed stack objects rather than through explicit finally clauses.<span style="mso-spacerun: yes">&nbsp; </span>You should be using ‘finally’ clauses to<br />
guarantee consistency of application state far more frequently than you use<br />
‘catch’ clauses.<span style="mso-spacerun: yes">&nbsp; </span>That’s because<br />
catch clauses increase the likelihood that developers will swallow exceptions<br />
that should be handled elsewhere, or perhaps should even be left unhandled.<span style="mso-spacerun: yes">&nbsp; </span>And if catch clauses don’t actually<br />
swallow an exception (i.e. they ‘rethrow’), they still create a poor debugging<br />
experience as we shall see.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} catch (Object o)<br />
{…}<o :p></o></font></span></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
pretty standard, too.<span style="mso-spacerun: yes">&nbsp; </span>One thing<br />
that might surprise some developers is that you can catch any instance that’s of<br />
type Object or derived from Object.<span style="mso-spacerun: yes">&nbsp;<br />
</span>However, there is a CLS rule that only subtypes of System.Exception<br />
should be thrown.<span style="mso-spacerun: yes">&nbsp; </span>In fact, C# is so<br />
eager for you to only deal with System.Exception that it doesn’t provide any<br />
access to the thrown object unless you are catching Exception or one of its<br />
subtypes.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>When you<br />
consider that only Exception and its subtypes have support for stack traces,<br />
HRESULT mapping, standard access to exception messages, and good support<br />
throughout the frameworks, then it’s pretty clear that you should restrict<br />
yourself to throwing and processing exceptions that derive from<br />
Exception.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In<br />
retrospect, perhaps we should have limited exception support to Exception rather<br />
than Object.<span style="mso-spacerun: yes">&nbsp; </span>Originally, we wanted<br />
the CLR to be a useful execution engine for more run-time libraries than just<br />
the.NET Frameworks.<span style="mso-spacerun: yes">&nbsp; </span>We imagined<br />
that different languages would execute on the CLR with their own particular<br />
run-time libraries.<span style="mso-spacerun: yes">&nbsp; </span>So we didn’t<br />
want to couple the base engine operations too tightly with CLS rules and<br />
constructs in the frameworks.<span style="mso-spacerun: yes">&nbsp; </span>Of<br />
course, now we understand that the commonality of the shared framework classes<br />
is a huge part of the value proposition of our managed environment.<span style="mso-spacerun: yes">&nbsp; </span>I suspect we would revisit our original<br />
design if we still could.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font size=2><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'; mso-bidi-font-family: Tahoma">try<br />
{</span></b><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'">…</span></b><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'; mso-bidi-font-family: Tahoma">} catch<br />
(Object o) if (expression) {</span></b><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'">…</span></b><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'; mso-bidi-font-family: Tahoma">}<o :p></o></span></b></font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
invented syntax, though I’m told it’s roughly what MC++ is considering.<span style="mso-spacerun: yes">&nbsp; </span>As far as I know, the only two.NET<br />
languages that currently support exception filters are VB.NET and – of course –<br />
ILASM.<span style="mso-spacerun: yes">&nbsp; </span>(We never build a managed<br />
construct without exposing it via ILDASM and ILASM in a manner that allows these<br />
two tools to round-trip between source and binary forms).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>VB.NET<br />
has sometimes been dismissed as a language that’s exclusively for less<br />
sophisticated developers.<span style="mso-spacerun: yes">&nbsp; </span>But the<br />
way this language exposes the advanced feature of exception filters is a great<br />
example of why that position is too simplistic.<span style="mso-spacerun: yes">&nbsp; </span>Of course, it is true that VB has<br />
historically done a superb job of providing an approachable toolset and<br />
language, which has allowed less sophisticated developers to be highly<br />
productive.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Anyway,<br />
isn’t this cool:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>Try<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>…try<br />
statements…<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>Catch e As<br />
InvalidOperationException When expressionFilter<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>…catch<br />
statements…<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>End<br />
Try<o :p></o></font></span></p>
	<p><span style="FONT-SIZE: 10pt; FONT-FAMILY: Tahoma">Of course, at the runtime<br />
level we cannot separate the test for the exception type expression and the<br />
filter expression.</span><span style="mso-spacerun: yes">&nbsp; </span>We only support<br />
a bare expression.<span style="mso-spacerun: yes">&nbsp; </span>So the VB<br />
compiler turns the above catch into <span style="FONT-SIZE: 10pt; FONT-FAMILY: Tahoma">something like</span> <span style="FONT-SIZE: 10pt; FONT-FAMILY: Tahoma">this, where $exception_obj is the<br />
implicit argument passed to the filter.<o :p></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>Catch When<br />
(IsInst($exception_obj, InvalidOperationException)<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>&amp;&amp; expressionFilter)<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>While<br />
we’re on the topic of exception handling in VB, have you ever wondered how VB<br />
.NET implements its On Error statement?</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>On Error { Goto {<br />
&lt;line&gt; | 0 | -1 } | Resume Next }<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Me<br />
neither.<span style="mso-spacerun: yes">&nbsp; </span>But I think it’s pretty<br />
obvious how to implement this sort of thing with an interpreter.<span style="mso-spacerun: yes">&nbsp; </span>You wait for something to go wrong, and<br />
then you consult the active “On Error” setting.<span style="mso-spacerun: yes">&nbsp; </span>If it tells you to “Resume Next”, you<br />
simply scan forwards to the next statement and away you go.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But in<br />
an SEH world, it’s a little more complicated.<span style="mso-spacerun: yes">&nbsp; </span>I tried some simple test cases with the<br />
VB 7.1 compiler.<span style="mso-spacerun: yes">&nbsp; </span>The resulting<br />
codegen is based on advancing a _Vb_t_CurrentStatement local variable to<br />
indicate the progression of execution through the statements.<span style="mso-spacerun: yes">&nbsp; </span>A single try/filter/catch covers<br />
execution of these statements.<span style="mso-spacerun: yes">&nbsp; </span>It<br />
was interesting to see that the ‘On Error’ command only applies to exceptions<br />
that derive from System.Exception.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The filter refuses to process any other exceptions.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So VB is<br />
nicely covered.<span style="mso-spacerun: yes">&nbsp; </span>But what if you did<br />
need to use exception filters from C#?<span style="mso-spacerun: yes">&nbsp;<br />
</span>Well, in V1 and V1.1, this would be quite difficult.<span style="mso-spacerun: yes">&nbsp; </span>But C# has announced a feature for their<br />
next release called anonymous methods.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This is a compiler feature that involves no CLR changes.<span style="mso-spacerun: yes">&nbsp; </span>It allows blocks of code to be mentioned<br />
inline via a delegate.<span style="mso-spacerun: yes">&nbsp; </span>This<br />
relieves the developer from the tedium of defining explicit methods and state<br />
objects that can be gathered into the delegate and the explicit sharing of this<br />
state.<span style="mso-spacerun: yes">&nbsp; </span>This and other seductive<br />
upcoming C# features are described at </font>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbconcprogramminglanguagefuturefeatures.asp <font face=Tahoma size=2>.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Using a<br />
mechanism like this, someone has pointed out that one could define delegates for<br />
try, filter and catch clauses and pass them to a shared chunk of ILASM.<span style="mso-spacerun: yes">&nbsp; </span>I love the way the C# compiler uses type<br />
inferencing to automatically deduce the delegate types.<span style="mso-spacerun: yes">&nbsp; </span>And it manufactures a state object to<br />
ensure that the locals and arguments of DoTryCatch are available to the “try<br />
statements”, “filter expression” and “catch statements”, almost as if everything<br />
was scoped in a single method body.<span style="mso-spacerun: yes">&nbsp;<br />
</span>(I say “almost” because any locals or arguments that are of byref,<br />
argiterator or typedbyref types cannot be disassociated from a stack without<br />
breaking safety.<span style="mso-spacerun: yes">&nbsp; </span>So these cases are<br />
disallowed). </font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>I’m<br />
guessing that access to filters from C# could look something like<br />
this:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>public void delegate<br />
__Try();<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>public Int32 delegate<br />
__Filter();<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>public void delegate<br />
__Catch();<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><o :p><font size=2>&nbsp;</font></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>// this reusable helper would<br />
be defined in ILASM or VB.NET:<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>void DoTryCatch(__Try t,<br />
__Filter f, __Catch c)<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><o :p><font size=2>&nbsp;</font></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>// And C# could then use it<br />
as follows:<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>void<br />
m(…arguments…)<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>{<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;<br />
</span>…locals…<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;<br />
</span>DoTryCatch(<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>{ …try<br />
statements…},<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>{ return<br />
filter_expression; },<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>{ …catch<br />
statements…}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>);<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>You may<br />
notice that I cheated a little bit.<span style="mso-spacerun: yes">&nbsp;<br />
</span>I didn’t provide a way for the ‘catch’ clause to mention the exception<br />
type that it is catching.<span style="mso-spacerun: yes">&nbsp; </span>Of<br />
course, this could be expressed as part of the filter, but that’s not really<br />
playing fair.<span style="mso-spacerun: yes">&nbsp; </span>I suspect the<br />
solution is to make DoTryCatch a generic method that has an unbound Type<br />
parameter.<span style="mso-spacerun: yes">&nbsp; </span>Then DoTryCatch&lt;T&gt;<br />
could be instantiated for a particular type.<span style="mso-spacerun: yes">&nbsp; </span>However, I haven’t actually tried this<br />
so I hate to pretend that it would work.<span style="mso-spacerun: yes">&nbsp;<br />
</span>I am way behind on understanding what we can and cannot do with generics<br />
in our next release, how to express this in ILASM, and how it actually works<br />
under the covers.<span style="mso-spacerun: yes">&nbsp; </span>Any blog on that<br />
topic is years away.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>While we<br />
are on the subject of interesting C# codegen, that same document on upcoming<br />
features also discusses iterators.<span style="mso-spacerun: yes">&nbsp;<br />
</span>These allow you to use the ‘yield’ statement to convert the normal pull<br />
model of defining iteration into a convenient push model.<span style="mso-spacerun: yes">&nbsp; </span>You can see the same ‘yield’ notion in<br />
Ruby.<span style="mso-spacerun: yes">&nbsp; </span>And I’m told that both<br />
languages have borrowed this from CLU, which pioneered the feature about the<br />
time that I was born.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>When you<br />
get your hands on an updated C# compiler that supports this handy construct, be<br />
sure to ILDASM your program and see how it’s achieved.<span style="mso-spacerun: yes">&nbsp; </span>It’s a great example of what a compiler<br />
can do to make life easier for a developer, so long as we’re willing to burn a<br />
few more cycles compared to a more prosaic loop construct.<span style="mso-spacerun: yes">&nbsp; </span>In today’s world, this is <i style="mso-bidi-font-style: normal">almost</i> always a sensible<br />
trade-off.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Okay,<br />
that last part has nothing to do with exceptions, does it?<span style="mso-spacerun: yes">&nbsp; </span>Let’s get back to the managed exception<br />
model.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} fault<br />
{…}<o :p></o></font></span></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Have you<br />
ever written code like this, to restrict execution of your finally clause to<br />
just the exceptional cases?</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>bool exceptional =<br />
true;<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try<br />
{<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>…body of<br />
try…<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>exceptional =<br />
false;<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>} finally<br />
{<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>if (exceptional)<br />
{…}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><o :p><font size=2>&nbsp;</font></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Or how<br />
about a catch with a rethrow, as an alternate technique for achieving finally<br />
behavior for just the exceptional cases:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><o :p><font size=2>&nbsp;</font></o></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try<br />
{<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>…<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>} catch<br />
{<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp; </span>…<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2><span style="mso-spacerun: yes">&nbsp;&nbsp;<br />
</span>rethrow;<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.5in"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In each<br />
case, you are accommodating for the fact that your language doesn’t expose fault<br />
blocks.<span style="mso-spacerun: yes">&nbsp; </span>In fact, I think the only<br />
language that exposes these is ILASM.<span style="mso-spacerun: yes">&nbsp;<br />
</span>A fault block is simply a finally clause that only executes in the<br />
exceptional case.<span style="mso-spacerun: yes">&nbsp; </span>It never executes<br />
in the non-exceptional case.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Incidentally, the first alternative is preferable to the second.<span style="mso-spacerun: yes">&nbsp; </span>The second approach terminates the first<br />
pass of exception handling.<span style="mso-spacerun: yes">&nbsp; </span>This is<br />
a fundamentally different semantics, which has a substantial impact on debugging<br />
and other operations.<span style="mso-spacerun: yes">&nbsp; </span>Let’s look at<br />
rethrow in more detail, to see why this is the case.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>Rethrow,<br />
restartable exceptions, debugging<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Gee, my<br />
language has rethrow, but no filter.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Why can’t I just treat the following constructs as equivalent?</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} filter (expression)<br />
catch (Exception e) {…}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} catch (Exception e) {<br />
if (!expression) rethrow; …}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In fact,<br />
‘rethrow’ tries hard to create the illusion that the initial exception handling<br />
is still in progress.<span style="mso-spacerun: yes">&nbsp; </span>It uses the<br />
same exception object.<span style="mso-spacerun: yes">&nbsp; </span>And it<br />
augments the stack trace associated with that exception object, so that it<br />
includes the portion of stack from the rethrow to the eventual catch.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Hmm, I<br />
guess I should have already mentioned that the stack trace of an Exception is<br />
intentionally restricted to the segment of stack from the throw to the<br />
catch.<span style="mso-spacerun: yes">&nbsp; </span>We do this for performance<br />
reasons, since part of the cost of an exception is linear with the depth of the<br />
stack that we capture.<span style="mso-spacerun: yes">&nbsp; </span>I’ll talk<br />
about the implications of exception performance later.<span style="mso-spacerun: yes">&nbsp; </span>Of course, you can use the<br />
System.Diagnostics.StackTrace class to gather the rest of the stack from the<br />
point of the catch, and then manually merge it into the stack trace from the<br />
Exception object.<span style="mso-spacerun: yes">&nbsp; </span>But this is a<br />
little clumsy and we have sometimes been asked to provide a helper to make this<br />
more convenient and less brittle to changes in the formatting of stack<br />
traces.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Incidentally, when you are playing around with stack traces (whether they<br />
are associated with exceptions, debugging, or explicit use of the StackTrace<br />
class), you will always find JIT inlining getting in your way.<span style="mso-spacerun: yes">&nbsp; </span>You can try to defeat the JIT inliner<br />
through use of indirected calls like function pointers, virtual methods,<br />
interface calls and delegates.<span style="mso-spacerun: yes">&nbsp; </span>Or<br />
you can make the called method “interesting” enough that the JIT decides it<br />
would be unproductive or too difficult to inline.<span style="mso-spacerun: yes">&nbsp; </span>All these techniques are flawed, and all<br />
of them will fail over time.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
correct way to control inlining is to use the<br />
MethodImpl(MethodImplOptions.NoInlining) pseudo-custom attribute from the<br />
System.Runtime.CompilerServices namespace.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>One way<br />
that a rethrow differs from a filter is with respect to resumable or restartable<br />
exceptions.<span style="mso-spacerun: yes">&nbsp; </span>We’ve already seen how<br />
SEH allows an exception filter to return EXCEPTION_CONTINUE_EXECUTION.<span style="mso-spacerun: yes">&nbsp; </span>This causes the faulting instruction to<br />
be restarted.<span style="mso-spacerun: yes">&nbsp; </span>Obviously it’s<br />
unproductive to do this unless the filter has first taken care of the faulting<br />
situation somehow.<span style="mso-spacerun: yes">&nbsp; </span>It could do this<br />
by changing the register state in the exception context so that a different<br />
value is dereferenced, or so that execution resumes at a different<br />
instruction.<span style="mso-spacerun: yes">&nbsp; </span>Or it could have<br />
modified the environment the program is running in, as with the VirtualProtect<br />
cases that I mentioned earlier.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In V1<br />
and V1.1, the managed exception model does not support restartable<br />
exceptions.<span style="mso-spacerun: yes">&nbsp; </span>In fact, I think that<br />
we set EXCEPTION_NONCONTINUABLE on some (but perhaps not all) of our exceptions<br />
to indicate this.<span style="mso-spacerun: yes">&nbsp; </span>There are several<br />
reasons why we don’t support restartable exceptions:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l8 level1 lfo9"><font face=Tahoma size=2>In order to repair a faulting situation, the exception<br />
 handler needs intimate knowledge about the execution environment.<span style="mso-spacerun: yes">&nbsp; </span>In managed code, we’ve gone to great<br />
 lengths to hide these details.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>For example, there is no architecture-neutral mapping from the IL<br />
 expression of stack-based execution to the register set of the underlying<br />
 CPU.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l8 level1 lfo9"><font face=Tahoma size=2>Restartability is often desired for asynchronous<br />
 exceptions.<span style="mso-spacerun: yes">&nbsp; </span>By ‘asynchronous’ I<br />
 mean that the exception is not initiated by an explicit call to ‘throw’ in the<br />
 code.<span style="mso-spacerun: yes">&nbsp; </span>Rather, it results from a<br />
 memory fault or an injected failure like Abort that can happen on any<br />
 instruction.<span style="mso-spacerun: yes">&nbsp; </span>Propagating a<br />
 managed exception, where this involves execution of a managed filter,<br />
 necessarily involves the potential for a GC.<span style="mso-spacerun: yes">&nbsp; </span>A JIT has some discretion over the<br />
 GC-safe points that it chooses to support in a method.<span style="mso-spacerun: yes">&nbsp; </span>Certainly the JIT must gather GC<br />
 information to report roots accurately at all call-sites.<span style="mso-spacerun: yes">&nbsp; </span>But the JIT normally isn’t required to<br />
 maintain GC info for every instruction.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>If any instruction might fault, and if any such fault could be resumed,<br />
 then the JIT would need GC info for all instructions in all methods.<span style="mso-spacerun: yes">&nbsp; </span>This would be expensive.<span style="mso-spacerun: yes">&nbsp; </span>Of course, ‘mov eax, ecx’ cannot fault<br />
 due to memory access issues.<span style="mso-spacerun: yes">&nbsp; </span>But<br />
 a surprising number of instructions are subject to fault if you consider all<br />
 of memory – including the stack – to be unmapped.<span style="mso-spacerun: yes">&nbsp; </span>And even ‘mov eax, ecx’ can fault due<br />
 to a Thread.Abort.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you<br />
were paying attention to that last bullet, you might be wondering how<br />
asynchronous exceptions could avoid GC corruption even without resumption.<span style="mso-spacerun: yes">&nbsp; </span>After all, the managed filter will still<br />
execute and we know that the JIT doesn’t have complete GC information for the<br />
faulting instruction.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Our<br />
current solution to this on X86 is rather ad hoc, but it does work.<span style="mso-spacerun: yes">&nbsp; </span>First, we constrain the JIT to never<br />
flow the contents of the scratch registers between a ‘try’ clause and any of the<br />
exception clauses (‘filter’, ‘finally’, ‘fault’ and ‘catch’).<span style="mso-spacerun: yes">&nbsp; </span>The scratch registers in this case are<br />
EAX, ECX, EDX and sometimes EBP.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Our JIT compiler decides, method-by-method, whether to use EBP as a<br />
stack-frame register or a scratch register.<span style="mso-spacerun: yes">&nbsp; </span>Of course, EBP isn’t really a scratch<br />
register since callees will preserve it for us, but you can see where I’m<br />
going.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Now when<br />
an asynchronous exception occurs, we can discard the state of all the scratch<br />
registers.<span style="mso-spacerun: yes">&nbsp; </span>In the case of EAX, ECX<br />
&amp; EDX, we can unconditionally zero them in the register context that is<br />
flowed via exception propagation.<span style="mso-spacerun: yes">&nbsp;<br />
</span>In the case of EBP, we only zero it if we aren’t using EBP as a frame<br />
register.<span style="mso-spacerun: yes">&nbsp; </span>When we execute a managed<br />
handler, we can now report GC roots based on the GC information that’s<br />
associated with the handler’s instruction pointer.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
downside to this approach, other than its ad hoc nature, is that it constrains<br />
the codegen of any method that contains exception handlers.<span style="mso-spacerun: yes">&nbsp; </span>At some point we may have to model<br />
asynchronous exceptions more accurately, or expand the GC information spewed by<br />
the JIT compiler, or a combination, so that we can enable better code generation<br />
in the presence of exceptions.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We’ve<br />
already seen how VB.NET can use a filter and explicit logic flow from a catch<br />
clause to create the illusion of restartable exceptions to support ‘On Error<br />
Resume Next’.<span style="mso-spacerun: yes">&nbsp; </span>But this should not<br />
be confused with true restartability.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Before<br />
we leave the topic of rethrow, we should briefly consider the InnerException<br />
property of System.Exception.<span style="mso-spacerun: yes">&nbsp; </span>This<br />
allows one exception to be wrapped up in the state of another exception.<span style="mso-spacerun: yes">&nbsp; </span>A couple of important places where we<br />
take advantage of this are reflection and class construction.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>When you<br />
perform late-bound invocation via reflection (e.g. Type.InvokeMember or<br />
MethodInfo.Invoke), exceptions can occur in two places:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; tab-stops: list.5in; mso-list: l6 level1 lfo4"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>The reflection infrastructure may<br />
decide that it cannot satisfy your request, perhaps because you passed the wrong<br />
number of arguments, or the member lookup failed, or you are invoking on someone<br />
else’s private members.<span style="mso-spacerun: yes">&nbsp; </span>That last<br />
one sounds vaguely dirty.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; tab-stops: list.5in; mso-list: l6 level1 lfo4"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>The late-bound invocation might<br />
work perfectly, but the target method you called may throw an exception back at<br />
you.<span style="mso-spacerun: yes">&nbsp; </span>Reflection must faithfully<br />
give you that exception as the result of the call.<span style="mso-spacerun: yes">&nbsp; </span>Returning it as an outbound argument,<br />
rather than throwing it at you, would be dangerous.<span style="mso-spacerun: yes">&nbsp; </span>We would lose one of the wonderful<br />
properties of exceptions, which is that they are hard to ignore.<span style="mso-spacerun: yes">&nbsp; </span>Error codes are constantly being<br />
swallowed or otherwise ignored, leading to fragile execution.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
problem is that these two sources of exceptions are ambiguous.<span style="mso-spacerun: yes">&nbsp; </span>There must be some way to tell whether<br />
the invocation attempt failed or whether the target of the invocation<br />
failed.<span style="mso-spacerun: yes">&nbsp;&nbsp; </span>Reflection<br />
disambiguates these cases by using an instance of<br />
System.Reflection.TargetInvocationException for the case where the invoked<br />
method threw an exception.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
InnerException property of this instance is the exception that was thrown by the<br />
invoked method.<span style="mso-spacerun: yes">&nbsp; </span>If you get any<br />
exceptions from a late-bound invocation other than TargetInvocationException,<br />
those other exceptions indicate problems with the late-bound dispatch attempt<br />
itself.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Something similar happens with TypeInitializationException.<span style="mso-spacerun: yes">&nbsp; </span>If a class constructor (.cctor) method<br />
fails, we capture that exception as the InnerException of a<br />
TypeInitializationException.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Subsequent attempts to use that class in this AppDomain from this or<br />
other threads will have that same TypeInitializationException instance thrown at<br />
them.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So<br />
what’s the difference between the following three constructs, where the<br />
overloaded constructor for MyExcep is placing its argument into<br />
InnerException:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} catch (Exception e) {<br />
if (expr) rethrow; …}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} catch (Exception e) {<br />
if (expr) throw new MyExcep(); …}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>try {…} catch (Exception e) {<br />
if (expr) throw new MyExcep(e); …}<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Well,<br />
the 2<sup>nd</sup> form is losing information.<span style="mso-spacerun: yes">&nbsp; </span>The original exception has been<br />
lost.<span style="mso-spacerun: yes">&nbsp; </span>It’s hard to recommend that<br />
approach.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Between<br />
the 1<sup>st</sup> and 3<sup>rd</sup> forms, I suppose it depends on whether the<br />
intermediary can add important information by wrapping the original exception in<br />
a MyExcep instance.<span style="mso-spacerun: yes">&nbsp; </span>Even if you are<br />
adding value with MyExcep, it’s still important to preserve the original<br />
exception information in the InnerException so that sophisticated programs and<br />
developers can determine the complete cause of the error.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Probably<br />
the biggest impact from terminating the first pass of exception handling early,<br />
as with the examples above, is on debugging.<span style="mso-spacerun: yes">&nbsp; </span>Have you ever attached a debugger to a<br />
process that has failed with an unhandled exception?<span style="mso-spacerun: yes">&nbsp; </span>When everything goes perfectly, the<br />
debugger pops up sitting in the context of the RaiseException or trap<br />
condition.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>That’s<br />
so much better than attaching the debugger and ending up on a ‘rethrow’<br />
statement.<span style="mso-spacerun: yes">&nbsp; </span>What you really care<br />
about is the state of the process when the initial exception was thrown.<span style="mso-spacerun: yes">&nbsp; </span>But the first pass has terminated and<br />
the original state of the world may have been lost.<span style="mso-spacerun: yes">&nbsp; </span>It’s clear why this happens, based on<br />
the two pass nature of exception handling.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Actually, the determination of whether or not the original state of the<br />
world has been lost or merely obscured is rather subtle.<span style="mso-spacerun: yes">&nbsp; </span>Certainly the current instruction<br />
pointer is sitting in the rethrow rather than on the original fault.<span style="mso-spacerun: yes">&nbsp; </span>But remember how filter and finally<br />
clauses are executed with an EBP that puts the containing method’s locals in<br />
scope… and an ESP that still contains the original faulting method?<span style="mso-spacerun: yes">&nbsp; </span>It turns out that the catching handler<br />
has some discretion on whether to pop ESP before executing the catch clause or<br />
instead to delay the pop until the catch clause is complete.<span style="mso-spacerun: yes">&nbsp; </span>The managed handler currently pops the<br />
stack before calling the catch clause, so the original state of the exception is<br />
truly lost.<span style="mso-spacerun: yes">&nbsp; </span>I believe the unmanaged<br />
C++ handler delays the pop until the catch completes, so recovering the state of<br />
the world for the original exception is tricky but possible.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Regardless, every time you catch and rethrow, you inflict this bitter<br />
disappointment on everyone who debugs through your code.<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, there are a number of<br />
places in managed code where this disappointment is unavoidable.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The most<br />
unfortunate place is at AppDomain boundaries.<span style="mso-spacerun: yes">&nbsp; </span>I’ve already explained at </font>http://blogs.gotdotnet.com/cbrumme/PermaLink.aspx/56dd7611-a199-4a1f-adae-6fac4019f11b <font face=Tahoma size=2> why the Isolation requirement of AppDomains forces us to<br />
marshal most exceptions across the boundary.<span style="mso-spacerun: yes">&nbsp; </span>And we’ve just discussed how reflection<br />
and class construction terminate the first pass by wrapping exceptions as the<br />
InnerException of an outer exception.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>One<br />
alternative is to trap on all first-chance exceptions.<span style="mso-spacerun: yes">&nbsp; </span>That’s because debuggers can have first<br />
crack at exceptions before the vectored exception handler even sees the<br />
fault.<span style="mso-spacerun: yes">&nbsp; </span>This certainly gives you the<br />
ability to debug each exception in the context in which it was thrown.<span style="mso-spacerun: yes">&nbsp; </span>But you are likely to see a lot of<br />
exceptions in the debugger this way!</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In fact,<br />
throughout V1 of the runtime, the ASP.NET team ran all their stress suites with<br />
a debugger attached and configured to trap on first-chance Access Violations<br />
(“sxe av”).<span style="mso-spacerun: yes">&nbsp; </span>Normally an AV in<br />
managed code is converted to a NullReferenceException and then handled like any<br />
other managed exception.<span style="mso-spacerun: yes">&nbsp; </span>But<br />
ASP.NET’s settings caused stress to trap in the debugger for any such AV.<span style="mso-spacerun: yes">&nbsp; </span>So their team enforced a rule that all<br />
their suites (including all dependencies throughout FX) must avoid such<br />
faults.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>It’s an<br />
approach that worked for them, but it’s hard to see it working more<br />
broadly.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Instead,<br />
over time we need to add new hooks to our debuggers so they can trap on just the<br />
exceptions you care about.<span style="mso-spacerun: yes">&nbsp; </span>This<br />
might involve trapping exceptions that are escaping your code or are being<br />
propagated into your code (for some definition of ‘your code’).<span style="mso-spacerun: yes">&nbsp; </span>Or it might involve trapping exceptions<br />
that escape an AppDomain or that are propagated into an AppDomain.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
above text has described a pretty complete managed exception model.<span style="mso-spacerun: yes">&nbsp; </span>But there’s one feature that’s<br />
conspicuously absent.<span style="mso-spacerun: yes">&nbsp; </span>There’s no<br />
way for an API to document the legal set of exceptions that can escape from<br />
it.<span style="mso-spacerun: yes">&nbsp; </span>Some languages, like C++,<br />
support this feature.<span style="mso-spacerun: yes">&nbsp; </span>Other<br />
languages, like Java, mandate it.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Of course, you could attach Custom Attributes to your methods to indicate<br />
the anticipated exceptions, but the CLR would not enforce this.<span style="mso-spacerun: yes">&nbsp; </span>It would be an opt-in discipline that<br />
would be of dubious value without global buy-in and guaranteed<br />
enforcement.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
another of those religious language debates.<span style="mso-spacerun: yes">&nbsp; </span>I don’t want to rehash all the reasons<br />
for and against documenting thrown exceptions.<span style="mso-spacerun: yes">&nbsp; </span>I personally don’t believe the<br />
discipline is worth it, but I don’t expect to change the minds of any<br />
proponents.<span style="mso-spacerun: yes">&nbsp; </span>It doesn’t<br />
matter.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>What<br />
does matter is that disciplines like this must be applied universally to have<br />
any value.<span style="mso-spacerun: yes">&nbsp; </span>So we either need to<br />
dictate that everyone follow the discipline or we must so weaken it that it is<br />
worthless even for proponents of it.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And since one of our goals is high productivity, we aren’t going to<br />
inflict a discipline on people who don’t believe in it – particularly when that<br />
discipline is of debatable value.<span style="mso-spacerun: yes">&nbsp;<br />
</span>(It is debatable in the literal sense, since there are many people on<br />
both sides of the argument).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>To me,<br />
this is rather like ‘const’ in C++.<span style="mso-spacerun: yes">&nbsp;<br />
</span>People often ask why we haven’t bought into this notion and applied it<br />
broadly throughout the managed programming model and frameworks.<span style="mso-spacerun: yes">&nbsp; </span>Once again, ‘const’ is a religious<br />
issue.<span style="mso-spacerun: yes">&nbsp; </span>Some developers are fierce<br />
proponents of it and others find that the modest benefit doesn’t justify the<br />
enormous burden.<span style="mso-spacerun: yes">&nbsp; </span>And, once again,<br />
it must be applied broadly to have value.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Now in<br />
C++ it’s possible to ‘const-ify’ the low level runtime library and services, and<br />
then allow client code to opt-in or not.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And when the client code runs into places where it must lose ‘const’ in<br />
order to call some non-const-ified code, it can simply remove ‘const’ via a<br />
dirty cast.<span style="mso-spacerun: yes">&nbsp; </span>We have all done this<br />
trick, and it is one reason that I’m not particularly in favor of ‘const’<br />
either.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But in a<br />
managed world, ‘const’ would only have value if it were enforced by the<br />
CLR.<span style="mso-spacerun: yes">&nbsp; </span>That means the verifier would<br />
prevent you from losing ‘const’ unless you explicitly broke type safety and were<br />
trusted by the security system to do so.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Until more than 80% of developers are clamoring for an enforced ‘const’<br />
model throughout the managed environment, you aren’t going to see us added<br />
it.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>Foray into<br />
C++ Exceptions<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>C++<br />
exposes its own exception model, which is distinct from the __try / __except /<br />
__finally exposure of SEH.<span style="mso-spacerun: yes">&nbsp; </span>This is<br />
done through auto-destruction of stack-allocated objects and through the ‘try’<br />
and ‘catch’ keywords.<span style="mso-spacerun: yes">&nbsp; </span>Note that<br />
there are no double-underbars and there is no support for filters other than<br />
through matching of exception types.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Of course, under the covers it’s still SEH.<span style="mso-spacerun: yes">&nbsp; </span>So there’s still an FS:[0] handler (on<br />
X86).<span style="mso-spacerun: yes">&nbsp; </span>But the C++ compiler<br />
optimizes this by only emitting a single SEH handler per method regardless of<br />
how many try/catch/finally clauses you use.<span style="mso-spacerun: yes">&nbsp; </span>The compiler emits a table to indicate<br />
to a common service in the C-runtime library where the various try, catch and<br />
finally clauses can be found in the method body.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of<br />
course, one of the biggest differences between SEH and the C++ exception model<br />
is that C++ allows you to throw and catch objects of types defined in your<br />
application.<span style="mso-spacerun: yes">&nbsp; </span>SEH only lets you<br />
throw 32-bit exception codes.<span style="mso-spacerun: yes">&nbsp; </span>You<br />
can use _set_se_translator to map SEH codes into the appropriate C++ classes in<br />
your application.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>A large<br />
part of the C++ exception model is implicit.<span style="mso-spacerun: yes">&nbsp; </span>Rather than use explicit try / finally /<br />
catch clauses, this language encourages use of auto-destructed local<br />
variables.<span style="mso-spacerun: yes">&nbsp; </span>Whether the method<br />
unwinds via a non-exceptional return statement or an exception being thrown,<br />
that local object will auto-destruct.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
basically a ‘finally’ clause that’s been wrapped up in a more useful language<br />
construct.<span style="mso-spacerun: yes">&nbsp; </span>Auto-destruction occurs<br />
during the second pass of SEH, as you would expect.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Have you<br />
noticed that the C++ exception you throw is often a stack-allocated local?<span style="mso-spacerun: yes">&nbsp; </span>And that if you explicitly catch it,<br />
this catch is also with a stack-allocated object?<span style="mso-spacerun: yes">&nbsp; </span>Did you ever wake up at night in a cold<br />
sweat, wondering whether a C++ in-flight exception resides on a piece of stack<br />
that’s already been popped?<span style="mso-spacerun: yes">&nbsp; </span>Of<br />
course not.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In fact,<br />
we’ve now seen enough of SEH to understand how the exception always remains in a<br />
section of the stack above ESP (i.e. within the bounds of the stack).<span style="mso-spacerun: yes">&nbsp; </span>Prior to the throw, the exception is<br />
stack-allocated within the active frame.<span style="mso-spacerun: yes">&nbsp;<br />
</span>During the first pass of SEH, nothing gets popped.<span style="mso-spacerun: yes">&nbsp; </span>When the filters execute, they are<br />
pushed deeper on the stack than the throwing frame.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>When a<br />
frame declares it will catch the exception, the second pass starts.<span style="mso-spacerun: yes">&nbsp; </span>Even here, the stack doesn’t<br />
unwind.<span style="mso-spacerun: yes">&nbsp; </span>Then, before resetting the<br />
stack pointer, the C++ handler can copy-construct the original exception from<br />
the piece of stack that will be popped into the activation frame that will be<br />
uncovered.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you<br />
are an expert in unmanaged C++ exceptions, you will probably be interested to<br />
learn of the differences between managed C++ exceptions and unmanaged C++<br />
exceptions.<span style="mso-spacerun: yes">&nbsp; </span>There’s a good write-up<br />
of these differences at </font>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcmex/html/vccondifferencesinexceptionhandlingbehaviorundermanagedexceptionsforc.asp <font face=Tahoma size=2>.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>A Single<br />
Managed Handler<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>We’ve<br />
already seen how the C++ compiler can emit one SEH handler per method and reuse<br />
it for all the exception blocks in that method.<span style="mso-spacerun: yes">&nbsp; </span>The handler can do this by consulting a<br />
side table that indicates how the various clauses map to instruction sequences<br />
within that method.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In the<br />
managed environment, we can take this even further.<span style="mso-spacerun: yes">&nbsp; </span>We maintain a boundary between managed<br />
and unmanaged code for many reasons, like synchronization with the garbage<br />
collector, to enable stack crawling through managed code, and to marshal<br />
arguments properly.<span style="mso-spacerun: yes">&nbsp; </span>We have<br />
modified this boundary to erect a single SEH handler at every unmanaged -&gt;<br />
managed call in.<span style="mso-spacerun: yes">&nbsp; </span>For the most part,<br />
we must do this without compiler support since many of our transitions occur<br />
through dynamically generated machine code.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The cost<br />
of modifying the SEH chain during calls into managed code is quickly amortized<br />
as we call freely between managed methods.<span style="mso-spacerun: yes">&nbsp;<br />
</span>So the immediate cost of pushing FS:[0] handlers on method entry is<br />
negligible for managed code.<span style="mso-spacerun: yes">&nbsp; </span>But<br />
there is still an impact on the quality of the generated code.<span style="mso-spacerun: yes">&nbsp; </span>We saw part of this impact in the<br />
discussion of register usage across exception clauses to remain<br />
GC-safe.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of<br />
course, the biggest cost of exceptions is when you actually throw one.<span style="mso-spacerun: yes">&nbsp; </span>I’ll return to this near the end of the<br />
blog.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>Flow<br />
Control<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Here’s<br />
an interesting scenario that came up recently.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Let’s<br />
say we drive the first pass of exception propagation all the way to the end of<br />
the handler chain and we reach the unhandled exception backstop.<span style="mso-spacerun: yes">&nbsp; </span>That backstop will probably pop a dialog<br />
in the first pass, saying that the application has suffered an unhandled<br />
exception.<span style="mso-spacerun: yes">&nbsp; </span>Depending on how the<br />
system is configured, the dialog may allow us to terminate the process or debug<br />
it.<span style="mso-spacerun: yes">&nbsp; </span>Let’s say we choose<br />
Terminate.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Now the<br />
2<sup>nd</sup> pass begins.<span style="mso-spacerun: yes">&nbsp; </span>During<br />
the 2<sup>nd</sup> pass, all our finally clauses can execute.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>What if<br />
one of those 2<sup>nd</sup> pass ‘finally’ clauses throws a new exception?<span style="mso-spacerun: yes">&nbsp; </span>We’re going to start a new exception<br />
propagation from this location – with a new Exception instance.<span style="mso-spacerun: yes">&nbsp; </span>When we drive this new Exception up the<br />
chain, we may actually find a handler that will swallow the second<br />
exception.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If this<br />
is the case, the process won’t terminate due to that first exception. <span style="mso-spacerun: yes">&nbsp;</span>This is despite the fact that SEH told<br />
the user we had an unhandled exception, and the user told us to terminate the<br />
process.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
surprising, to say the least.<span style="mso-spacerun: yes">&nbsp; </span>And<br />
this behavior is possible, regardless of whether managed or unmanaged exceptions<br />
are involved.<span style="mso-spacerun: yes">&nbsp; </span>The mechanism for SEH<br />
is well-defined and the exception model operates within those rules.<span style="mso-spacerun: yes">&nbsp; </span>An application should avoid certain<br />
(ab)uses of this mechanism, to avoid confusion.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Indeed,<br />
we have prohibited some of those questionable uses in managed code.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In<br />
unmanaged, you should never return from a finally.<span style="mso-spacerun: yes">&nbsp; </span>In an exceptional execution of a<br />
finally, a return has the effect of terminating the exception processing.<span style="mso-spacerun: yes">&nbsp; </span>The catch handler never sees its<br />
2<sup>nd</sup> pass and the exception is effectively swallowed.<span style="mso-spacerun: yes">&nbsp; </span>Conversely, in a non-exceptional<br />
execution of a finally, a return has the effect of replacing the method’s return<br />
value with the return value from the finally.<span style="mso-spacerun: yes">&nbsp; </span>This is likely to cause developer<br />
confusion.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So in<br />
managed code we’ve made it impossible for you to return from a finally<br />
clause.<span style="mso-spacerun: yes">&nbsp; </span>The full rules for flow<br />
control involving managed exception clauses should be found at Section 12.4.2.8<br />
of ECMA Partition I (</font>http://msdn.microsoft.com/net/ecma/ <font face=Tahoma size=2>).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>However,<br />
it is possible to throw from a managed finally clause.<span style="mso-spacerun: yes">&nbsp; </span>(In general, it’s very hard to<br />
confidently identify regions of managed code where exceptions cannot be<br />
thrown).<span style="mso-spacerun: yes">&nbsp; </span>And this can have the<br />
effect of replacing the exception that was in flight with a new 1<sup>st</sup><br />
and 2<sup>nd</sup> pass sweep, as described above.<span style="mso-spacerun: yes">&nbsp; </span>This is the ExceptionCollidedUnwind<br />
situation that is mentioned in the EXCEPTION_DISPOSITION enumeration.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The C++<br />
language takes a different approach to exceptions thrown from the 2<sup>nd</sup><br />
pass.<span style="mso-spacerun: yes">&nbsp; </span>We’ve already seen that C++<br />
autodestructors execute during the 2<sup>nd</sup> pass of exception<br />
handling.<span style="mso-spacerun: yes">&nbsp; </span>If you’ve ever thrown an<br />
exception from the destructor, when that destructor is executed as part of an<br />
exception unwind, then you have already learned a painful lesson.<span style="mso-spacerun: yes">&nbsp; </span>The C++ behavior for this situation is<br />
to terminate the process via a termination handler.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In<br />
unmanaged C++, this means that developers must follow great discipline in the<br />
implementation of their destructors.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Since eventually those destructors might run in the context of exception<br />
backout, those destructors should never allow an exception to escape them.<span style="mso-spacerun: yes">&nbsp; </span>That’s painful, but presumably<br />
achievable.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In<br />
managed C++, I’ve already mentioned that it’s very hard to identify regions<br />
where exceptions cannot occur.<span style="mso-spacerun: yes">&nbsp; </span>The<br />
ability to prevent (asynchronous and resource) exceptions over limited ranges of<br />
code is something we would like to enable at some point in the future, but it<br />
just isn’t practical in V1 and V1.1.<span style="mso-spacerun: yes">&nbsp;<br />
</span>It’s way too easy for an out-of-memory or type-load or<br />
class-initialization or thread-abort or appdomain-unload or similar exception to<br />
intrude.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Finally,<br />
it’s possible for exceptions to be thrown during execution of a filter.<span style="mso-spacerun: yes">&nbsp; </span>When this happens in an OS SEH context,<br />
it results in the ExceptionNestedException situation that is mentioned in the<br />
EXCEPTION_DISPOSITION enumeration.<span style="mso-spacerun: yes">&nbsp;<br />
</span>The managed exception model took a different approach here.<span style="mso-spacerun: yes">&nbsp; </span>We’ve already seen that an MSVC filter<br />
clause has three legal returns values (resume execution, continue search, and<br />
execute handler).<span style="mso-spacerun: yes">&nbsp; </span>If a managed<br />
filter throws an exception, we contain that exception and consider the filter to<br />
have replied “No, I don’t want to handle this one.<span style="mso-spacerun: yes">&nbsp; </span>Continue searching for a<br />
handler”.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
a reasonable interpretation in all cases, but it falls out particularly well for<br />
stack overflow.<span style="mso-spacerun: yes">&nbsp; </span>With the historical<br />
OS support for stack overflow, it’s very hard to reliably execute backout<br />
code.<span style="mso-spacerun: yes">&nbsp; </span>As I’ve mentioned in other<br />
blogs, you may only have one 4K page of stack available for this purpose.<span style="mso-spacerun: yes">&nbsp; </span>If you blow that page, the process is<br />
terminated.<span style="mso-spacerun: yes">&nbsp; </span>It’s very hard to<br />
execute managed filters reliably within such a limited region.<span style="mso-spacerun: yes">&nbsp; </span>So a reasonable approach is to consider<br />
the filters to have themselves thrown a StackOverflowException and for us to<br />
interpret this as “No, I don’t want to handle this one.”</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In a<br />
future version, we would like to provide a more defensible and useful mechanism<br />
for handling stack overflow from managed code. </font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>Error<br />
Handling without Exceptions<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So we’ve<br />
seen how SEH and C++ and managed exceptions all interoperate.<span style="mso-spacerun: yes">&nbsp; </span>But not all error handling is based on<br />
exceptions.<span style="mso-spacerun: yes">&nbsp; </span>When we consider<br />
Windows, there are two other error handling systems that the CLR can<br />
interoperate with.<span style="mso-spacerun: yes">&nbsp; </span>These are the<br />
Get/SetLastError mechanism used by the OS and the HRESULT / IErrorInfo mechanism<br />
used by COM.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Let’s<br />
look at the GetLastError mechanism first, because it’s relatively simple.<span style="mso-spacerun: yes">&nbsp; </span>A number of OS APIs indicate failure by<br />
returning a sentinel value.<span style="mso-spacerun: yes">&nbsp; </span>Usually<br />
this sentinel value is -1 or 0 or 1, but the details vary depending on the<br />
API.<span style="mso-spacerun: yes">&nbsp; </span>This sentinel value indicates<br />
that the client can call GetLastError() to recover a more detailed OS status<br />
code.<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, it’s sometimes<br />
hard to know which APIs participate in the GetLastError protocol.<span style="mso-spacerun: yes">&nbsp; </span>Theoretically this information is always<br />
documented in MSDN and is consistent from one version of the OS to the next –<br />
including between the NT and Win95-based OSes.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The real<br />
issue occurs when you PInvoke to one of these methods.<span style="mso-spacerun: yes">&nbsp; </span>The OS API latches any failure codes<br />
with SetLastError.<span style="mso-spacerun: yes">&nbsp; </span>Now on the<br />
return path of the PInvoke, we may be calling various OS services and managed<br />
services to marshal the outbound arguments.<span style="mso-spacerun: yes">&nbsp; </span>We may be synchronizing with a pending<br />
GC, which could involve a blocking operation like WaitForSingleObject.<span style="mso-spacerun: yes">&nbsp; </span>Somewhere in here, we may call another<br />
OS API that itself latches an error code (or the absence of an error code)<br />
through its own call to SetLastError.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So by<br />
the time we return to some managed code that can generate up a new PInvoke stub<br />
to call GetLastError, you can be sure that the original error code is long<br />
gone.<span style="mso-spacerun: yes">&nbsp; </span>The solution is to tag your<br />
PInvoke declaration to indicate that it should participate in the GetLastError<br />
protocol.<span style="mso-spacerun: yes">&nbsp; </span>This tells the PInvoke<br />
call to capture the error as part of the return path, before any other OS calls<br />
on this thread have an opportunity to erase it or replace it.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This<br />
protocol works well for PInvokes.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Unfortunately, we do not have a way to tag IJW VTFixup stubs in the same<br />
way.<span style="mso-spacerun: yes">&nbsp; </span>So when you make managed -&gt;<br />
unmanaged calls via MC++ IJW, there isn’t a convenient and reliable way to<br />
recover a detailed OS status code on the return path.<span style="mso-spacerun: yes">&nbsp; </span>Obviously this is something we would<br />
like to address in some future version, though without blindly inflicting the<br />
cost of a GetLastError on all managed -&gt; unmanaged transitions through<br />
IJW.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font face=Tahoma></font><font size=2>COM Error<br />
Handling<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>To<br />
understand how the CLR interoperates with COM HRESULTs, we must first review how<br />
PreserveSig is used to modify the behavior of PInvoke and COM<br />
Interop.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Normally, COM signatures return an HRESULT error code.<span style="mso-spacerun: yes">&nbsp; </span>If the method needs to communicate some<br />
other result, this is typically expressed with an [out, retval] outbound<br />
argument.<span style="mso-spacerun: yes">&nbsp; </span>Of course, there are<br />
exceptions to this pattern.<span style="mso-spacerun: yes">&nbsp; </span>For<br />
example, IUnknown::AddRef and Release both return a count of the outstanding<br />
references, rather than an HRESULT.<span style="mso-spacerun: yes">&nbsp;<br />
</span>More importantly, HRESULTs can be used to communicate success codes as<br />
well as error codes.<span style="mso-spacerun: yes">&nbsp; </span>The two most<br />
typical success codes are S_OK and S_FALSE, though any HRESULT with the high bit<br />
reset is considered a success code.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>COM<br />
Interop normally transforms the unmanaged signature to create a managed<br />
signature where the [out, retval] argument becomes the managed return<br />
value.<span style="mso-spacerun: yes">&nbsp; </span>If there is no [out,<br />
retval], then the return type of the managed method is ‘void’.<span style="mso-spacerun: yes">&nbsp; </span>Then the COM Interop layer maps between<br />
failure HRESULTs and managed exceptions.<span style="mso-spacerun: yes">&nbsp;<br />
</span>Here’s a simple example:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>COM:<span style="mso-tab-count: 1">&nbsp; </span>HRESULT GetValue([out, retval] IUnknown<br />
**ppRet)<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>CLR:<span style="mso-tab-count: 1">&nbsp; </span>IUnknown<br />
GetValue()<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>However,<br />
the return value might be a DWORD-sized integer that should not be interpreted<br />
as an HRESULT.<span style="mso-spacerun: yes">&nbsp; </span>Or it might be an<br />
HRESULT – but one which must sometimes distinguish between different success<br />
codes.<span style="mso-spacerun: yes">&nbsp; </span>In these cases, PreserveSig<br />
can be specified on the signature and it will be preserved on the managed side<br />
as the traditional COM signature.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of<br />
course, the same can happen with PInvoke signatures.<span style="mso-spacerun: yes">&nbsp; </span>Normally a DLL export like Ole32.dll’s<br />
CoGetMalloc would have its signature faithfully preserved.<span style="mso-spacerun: yes">&nbsp; </span>Presumably the transformation would be<br />
something like this:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>DLL:<span style="mso-tab-count: 1">&nbsp; </span>HRESULT CoGetMalloc(DWORD c, [out,<br />
retval] IMalloc **ppRet)<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><span style="FONT-FAMILY: 'Lucida Console'"><font size=2>CLR:<span style="mso-tab-count: 1">&nbsp; </span>DWORD <span style="mso-spacerun: yes">&nbsp;&nbsp;</span>CoGetMalloc(DWORD c, ref IMalloc<br />
ppRet)<o :p></o></font></span></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If OLE32<br />
returns some sort of failure HRESULT from this call, it will be returned to the<br />
managed caller.<span style="mso-spacerun: yes">&nbsp; </span>If instead the<br />
application would prefer to get this error case automatically converted to a<br />
managed Exception, it can use PreserveSig to indicate this.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Huh?<span style="mso-spacerun: yes">&nbsp; </span>In the COM case<br />
PreserveSig means “give me the unconverted HRESULT signature”, but in the<br />
PInvoke case PreserveSig means “convert my HRESULTs into exceptions.”<span style="mso-spacerun: yes">&nbsp; </span>Why would we use the same flag to<br />
indicate exactly opposite semantics for these two interop layers?<span style="mso-spacerun: yes">&nbsp; </span>The reasons are, ahem, historical.<span style="mso-spacerun: yes">&nbsp; </span>The best way to think of PreserveSig is<br />
“give me the unusual transformation of my signature, as opposed to what is<br />
typical for the kind of interop I am doing.”</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So now<br />
we know how to obtain mappings between HRESULTs and managed exceptions for the<br />
typical COM Interop case (no PreserveSig) and the atypical PInvoke case<br />
(PreserveSig).<span style="mso-spacerun: yes">&nbsp; </span>But what are the<br />
details of that mapping?</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
exception subsystem in the CLR has mappings between COM errors, OS errors, and<br />
managed exception types.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Of<br />
course, sometimes we have a situation which doesn’t have a precise mapping.<span style="mso-spacerun: yes">&nbsp; </span>In the case of an HRESULT that isn’t<br />
associated with a specific managed Exception class, we convert it to an instance<br />
of COMException.<span style="mso-spacerun: yes">&nbsp; </span>In the case of an<br />
OS status code that isn’t associated with a specific managed Exception class, we<br />
convert it to an instance of SEHException.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Even for<br />
cases where we have a correspondence between a managed and unmanaged<br />
representation, the mapping won’t necessarily roundtrip.<span style="mso-spacerun: yes">&nbsp; </span>For instance, an AV in unmanaged code<br />
results in an SEH exception of code 0xC0000005.<span style="mso-spacerun: yes">&nbsp; </span>If this is driven through managed code,<br />
it will be mapped to the corresponding NullReferenceException class.<span style="mso-spacerun: yes">&nbsp; </span>If the propagation of this exception<br />
continues through managed code and further up the stack to an unmanaged SEH<br />
handler, the unmanaged code will see the original exception code of<br />
0xC0000005.<span style="mso-spacerun: yes">&nbsp; </span>So, when propagating<br />
through that sequence of handlers, we see a perfect roundtrip.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>But<br />
let’s change the scenario slightly, so that the original AccessViolation occurs<br />
in managed code.<span style="mso-spacerun: yes">&nbsp; </span>Now we have a<br />
NullReferenceException that is being propagated out to an unmanaged SEH handler<br />
further back on the stack.<span style="mso-spacerun: yes">&nbsp; </span>But this<br />
time the NullReferenceException will be mapped to an SEH exception code of<br />
0xE0434F4D.<span style="mso-spacerun: yes">&nbsp; </span>This is the managed<br />
exception code used for all managed exceptions.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Have you<br />
ever wondered where these exception codes come from?<span style="mso-spacerun: yes">&nbsp; </span>Well 0xE0434F4D is 0xE0+“COM”.<span style="mso-spacerun: yes">&nbsp; </span>Originally the CLR was called COM+<br />
2.0.<span style="mso-spacerun: yes">&nbsp; </span>When we changed the project<br />
name, we neglected to change the exception code.<span style="mso-spacerun: yes">&nbsp; </span>The unmanaged C++ exceptions use<br />
0xE06D7363, which is 0xE0+“msc”.<span style="mso-spacerun: yes">&nbsp;<br />
</span>You might also see 0xE0524F54 for 0xE0+“ROT” on Rotor builds.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
current mapping between OS status codes and managed exception types is quite<br />
limited.<span style="mso-spacerun: yes">&nbsp; </span>It contains standard<br />
transformations like:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_FLOAT_INEXACT_RESULT</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_FLOAT_INVALID_OPERATION</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_FLOAT_STACK_CHECK</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_FLOAT_UNDERFLOW<span style="mso-tab-count: 2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>=&gt; ArithmeticException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_FLOAT_OVERFLOW</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_INTEGER_OVERFLOW<span style="mso-tab-count: 2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>=&gt; OverflowException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_FLOAT_DIVIDE_BY_ZERO</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_INTEGER_DIVIDE_BY_ZERO<span style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>=&gt;<br />
DivideByZeroException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_FLOAT_DENORMAL_OPERAND<span style="mso-tab-count: 1">&nbsp;<br />
</span>=&gt; FormatException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_ACCESS_VIOLATION<span style="mso-tab-count: 2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>=&gt; NullReferenceException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_ARRAY_BOUNDS_EXCEEDED<span style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp; </span>=&gt;<br />
IndexOutOfRangeException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_NO_MEMORY<span style="mso-tab-count: 3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>=&gt; OutOfMemoryException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>STATUS_STACK_OVERFLOW<span style="mso-tab-count: 2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>=&gt; StackOverflowException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The<br />
HRESULT mappings are far more extensive.<span style="mso-spacerun: yes">&nbsp;<br />
</span>They include standard mappings to the well-known HRESULT values<br />
like:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>E_POINTER<span style="mso-tab-count: 4">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>=&gt; ArgumentNullException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>And they<br />
include mappings to CLR-defined HRESULTs in the 0x8013???? range that you’ve<br />
doubtless witnessed during your development and debugging.<span style="mso-spacerun: yes">&nbsp; </span>The managed platform has its own<br />
facility code for reserving a range of HRESULTs for our exclusive<br />
use.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>COR_E_ENTRYPOINTNOTFOUND<span style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span>=&gt; EntryPointNotFoundException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>And our<br />
mappings include a gathering of similar HRESULTs to a single managed<br />
exception.<span style="mso-spacerun: yes">&nbsp; </span>Here’s a particularly<br />
extensive gathering of 26 different HRESULTs to the FileLoadException<br />
class:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>FUSION_E_REF_DEF_MISMATCH</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>FUSION_E_INVALID_PRIVATE_ASM_LOCATION</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>COR_E_ASSEMBLYEXPECTED</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>FUSION_E_SIGNATURE_CHECK_FAILED</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>FUSION_E_ASM_MODULE_MISSING</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>FUSION_E_INVALID_NAME</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>FUSION_E_PRIVATE_ASM_DISALLOWED</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>COR_E_MODULE_HASH_CHECK_FAILED</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>COR_E_FILELOAD</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>SECURITY_E_INCOMPATIBLE_SHARE</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>SECURITY_E_INCOMPATIBLE_EVIDENCE</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>SECURITY_E_UNVERIFIABLE</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>COR_E_FIXUPSINEXE</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_TOO_MANY_OPEN_FILES)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_LOCK_VIOLATION)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_OPEN_FAILED)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_DISK_CORRUPT)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_UNRECOGNIZED_VOLUME)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_FILE_INVALID)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_DLL_INIT_FAILED)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT)</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>FUSION_E_CODE_DOWNLOAD_DISABLED</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>CORSEC_E_MISSING_STRONGNAME</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>INIT_E_DOWNLOAD_FAILURE</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>MSEE_E_ASSEMBLYLOADINPROGRESS<span style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp; </span>=&gt;<br />
FileLoadException</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There<br />
are some more observations we can make about the COM error handling<br />
approach.<span style="mso-spacerun: yes">&nbsp; </span>First, it should be<br />
obvious that the 32-bits of an HRESULT cannot uniquely define an arbitrary set<br />
of user-extensible error conditions.<span style="mso-spacerun: yes">&nbsp;<br />
</span>COM deals with this, in part, by including the interface that returns an<br />
HRESULT in the decision of how to interpret these 32-bits.<span style="mso-spacerun: yes">&nbsp; </span>This means that 0xE3021051 returned from<br />
IMyInterface is not the same error code as 0xE3201051 returned from<br />
IYourInterface.<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, it<br />
also means that each interface must be rigorous about the bit patterns it<br />
returns.<span style="mso-spacerun: yes">&nbsp; </span>Specifically, it would be<br />
very bad if the implementation of IMyInterface::m() happens to delegate to<br />
IYourInterface::n() and blindly return ‘n’s HRESULTs.<span style="mso-spacerun: yes">&nbsp; </span>Any HRESULTs returned from ‘n’ must<br />
somehow be mapped to the bit patterns that are legal to return from<br />
IMyInterface::m().<span style="mso-spacerun: yes">&nbsp; </span>If ‘n’ returns a<br />
bit pattern that IMyInterface::m() cannot map, then ‘m’ is obligated to convert<br />
the HRESULT to E_UNEXPECTED and return that.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>In other<br />
words, the uniqueness constraint for HRESULTs forces a painful discipline on all<br />
COM implementations that return HRESULTs.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And part of this discipline is to lose error information by mapping<br />
meaningful HRESULTs into E_UNEXPECTED if the context for interpreting those<br />
HRESULTs is being lost.<span style="mso-spacerun: yes">&nbsp; </span>(There is a<br />
well-defined set of system HRESULTs which are implicitly returnable from any<br />
interface.<span style="mso-spacerun: yes">&nbsp; </span>The bit pattern for<br />
E_UNEXPECTED is necessarily part of this set.<span style="mso-spacerun: yes">&nbsp; </span>The CLR facility code allows us to live<br />
in this privileged world with our own codes).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>The fact<br />
that most COM developers are unaware of this painful discipline and don’t follow<br />
it, just adds to the level of pain here.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Fortunately, COM supplements the limited expressibility and uniqueness of<br />
HRESULTs by using a second mechanism: IErrorInfo.<span style="mso-spacerun: yes">&nbsp; </span>And the COM Interop layer uses this<br />
supplementary mechanism when mapping to and from managed exception objects.<span style="mso-spacerun: yes">&nbsp; </span>In fact, System.Exception implements the<br />
IErrorInfo interface.<span style="mso-spacerun: yes">&nbsp; </span>When a<br />
managed exception is thrown to a COM client, the IErrorInfo of the Exception<br />
instance is available for the COM client to query.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Adam<br />
Nathan’s excellent book “.NET and COM – The Complete Interoperability Guide”<br />
describes how the IErrorInfo state is filled in from a managed exception in<br />
Chapter 16.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>There’s<br />
one more detail of COM Interop HRESULT mapping that warrants discussion.<span style="mso-spacerun: yes">&nbsp; </span>It’s good practice for all COM methods<br />
to return an HRESULT.<span style="mso-spacerun: yes">&nbsp; </span>But there are<br />
several famous violations of this rule, including IUnknown::AddRef and<br />
Release.<span style="mso-spacerun: yes">&nbsp; </span>More importantly, every<br />
developer can choose whether to follow this best practice.<span style="mso-spacerun: yes">&nbsp; </span>Some choose not to.<span style="mso-spacerun: yes">&nbsp; </span>And there are some typical cases, like<br />
event sinks, where we often see methods returning ‘void’ or ‘bool’.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This<br />
presents the COM Interop error mapping layer with a problem.<span style="mso-spacerun: yes">&nbsp; </span>If an exception occurs inside a managed<br />
implementation of a method with one of these signatures, it’s hard to convey the<br />
error information back to the COM caller.<span style="mso-spacerun: yes">&nbsp;<br />
</span>There are several choices available to that layer – none of them<br />
good:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; tab-stops: list.5in; mso-list: l4 level1 lfo5"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>1)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>Allow the managed exception to<br />
travel back through the COM caller, using the underlying SEH mechanism.<span style="mso-spacerun: yes">&nbsp; </span>This would work perfectly, but is<br />
strictly illegal.<span style="mso-spacerun: yes">&nbsp; </span>Well-behaved COM<br />
servers do not propagate exceptions out to their COM clients.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; tab-stops: list.5in; mso-list: l4 level1 lfo5"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>2)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>Swallow the managed<br />
exception.<span style="mso-spacerun: yes">&nbsp; </span>Propagate a return value<br />
with ‘0’ out to the COM client.<span style="mso-spacerun: yes">&nbsp;<br />
</span>This 0 value might get interpreted as a returned Boolean, integer, pUnk<br />
or other data type.<span style="mso-spacerun: yes">&nbsp; </span>In the case of<br />
a ‘void’ signature, it will simply be ignored.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal<br />
style="MARGIN: 0in 0in 0pt 0.5in; TEXT-INDENT: -0.25in; tab-stops: list.5in; mso-list: l4 level1 lfo5"><span style="mso-fareast-font-family: Tahoma; mso-bidi-font-family: Tahoma"></span><span style="mso-list: Ignore"><font face=Tahoma size=2>3)</font></span><span style="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
</span><font face=Tahoma size=2>Convert the exception object into<br />
an HRESULT value.<span style="mso-spacerun: yes">&nbsp; </span>Propagate that<br />
HRESULT out as the return value to the COM client.<span style="mso-spacerun: yes">&nbsp; </span>In the ‘void’ case, this will again be<br />
ignored.<span style="mso-spacerun: yes">&nbsp; </span>In the pUnk case, it will<br />
likely be dereferenced and subsequently cause an AccessViolation.<span style="mso-spacerun: yes">&nbsp; </span>(Failure HRESULTs have the high bit<br />
set.<span style="mso-spacerun: yes">&nbsp; </span>On Win32 the high 2 GB of<br />
address space are reserved for the kernel and are unavailable unless you run a<br />
/LARGEADDRESSAWARE process on a suitably booted system.<span style="mso-spacerun: yes">&nbsp; </span>On Win64, the low couple of GB of<br />
address are reserved and unavailable to detect this sort of mistake).</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>As you<br />
can see, all of these solutions are broken.<span style="mso-spacerun: yes">&nbsp; </span>Unfortunately, the most broken of the<br />
three is the last one… and that’s the one we currently follow.<span style="mso-spacerun: yes">&nbsp; </span>I suspect we will change our behavior<br />
here at some point.<span style="mso-spacerun: yes">&nbsp; </span>Until then, we<br />
rely on the fact that AddRef &amp; Release are specially handled and that the<br />
other cases are rare and are typically ‘void’ or ‘bool’ returns.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><b style="mso-bidi-font-weight: normal"><font size=2></font><font face=Tahoma>Performance<br />
and Trends<o :p></o></font></b></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Exceptions vs. error codes has always been a controversial topic.<span style="mso-spacerun: yes">&nbsp; </span>For the last 15 years, every team has<br />
argued whether their codebase should throw exceptions or return error<br />
codes.<span style="mso-spacerun: yes">&nbsp; </span>Hopefully nobody argues<br />
whether their team should mix both styles.<span style="mso-spacerun: yes">&nbsp;<br />
</span>That’s never desirable, though it often takes major surgery to migrate to<br />
a consistent plan.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>With any<br />
religious controversy, there are many arguments on either side.<span style="mso-spacerun: yes">&nbsp; </span>Some of them are related to:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l1 level1 lfo6"><font face=Tahoma size=2>A philosophy of what errors mean and whether they should be<br />
 expressed out-of-band with the method contract.</font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l1 level1 lfo6"><font face=Tahoma size=2>Performance.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>Exceptions have a direct cost when you actually throw and catch an<br />
 exception.<span style="mso-spacerun: yes">&nbsp; </span>They may also have an<br />
 indirect cost associated with pushing handlers on method entry.<span style="mso-spacerun: yes">&nbsp; </span>And they can often have an insidious<br />
 cost by restricting codegen opportunities.</font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l1 level1 lfo6"><font face=Tahoma size=2>It’s relatively easy to forget to check for a returned<br />
 error code.<span style="mso-spacerun: yes">&nbsp; </span>It’s much harder to<br />
 inadvertently swallow an exception without handling it (though we still find<br />
 developers doing so!)</font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l1 level1 lfo6"><font face=Tahoma size=2>Exceptions tend to capture far more information about the<br />
 cause and location of an error, though one could envision an error code system<br />
 that’s equally powerful.<span style="mso-spacerun: yes">&nbsp;<br />
 </span>(IErrorInfo anybody?)</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So<br />
what’s the right answer here?</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Well if<br />
you are building the kernel of an operating system, you should probably use<br />
error codes.<span style="mso-spacerun: yes">&nbsp; </span>You are a programming<br />
God who rarely makes mistakes, so it’s less likely that you will forget to check<br />
your return codes.<span style="mso-spacerun: yes">&nbsp; </span>And there are<br />
sound bootstrapping and performance reasons for avoiding exceptions within the<br />
kernel.<span style="mso-spacerun: yes">&nbsp; </span>In fact, some of the OS<br />
folks here think that SEH should be reserved for terrible “take down the<br />
process” situations.<span style="mso-spacerun: yes">&nbsp; </span>That may have<br />
been the original design point.<span style="mso-spacerun: yes">&nbsp; </span>But<br />
SEH is such a flexible system, and it is so entrenched as the basis for<br />
unmanaged C++ exceptions and managed exceptions, that it is no longer reasonable<br />
to restrict the mechanism to these critical failures.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>So, if<br />
you are not a programming God like those OS developers, you should consider<br />
using exceptions for your application errors.<span style="mso-spacerun: yes">&nbsp; </span>They are more powerful, more expressive,<br />
and less prone to abuse than error codes.<span style="mso-spacerun: yes">&nbsp;<br />
</span>They are one of the fundamental ways that we make managed programming<br />
more productive and less error prone. <span style="mso-spacerun: yes">&nbsp;</span>In fact, the CLR internally uses<br />
exceptions even in the unmanaged portions of the engine.<span style="mso-spacerun: yes">&nbsp; </span>However, there is a serious long term<br />
performance problem with exceptions and this must be factored into your<br />
decision.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Consider<br />
some of the things that happen when you throw an exception:</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<ul style="MARGIN-TOP: 0in" type=disc>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l3 level1 lfo7"><font face=Tahoma size=2>Grab a stack trace by interpreting metadata emitted by the<br />
 compiler to guide our stack unwind.</font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l3 level1 lfo7"><font size=2></font><font face=Tahoma>Run through a chain of handlers up the stack, calling<br />
 each handler twice.<span style="mso-spacerun: yes">&nbsp;<br />
 </span></font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l3 level1 lfo7"><font face=Tahoma size=2>Compensate for mismatches between SEH, C++ and managed<br />
 exceptions.</font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l3 level1 lfo7"><font face=Tahoma size=2>Allocate a managed Exception instance and run its<br />
 constructor.<span style="mso-spacerun: yes">&nbsp; </span>Most likely, this<br />
 involves looking up resources for the various error messages.</font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l3 level1 lfo7"><font face=Tahoma size=2>Probably take a trip through the OS kernel.<span style="mso-spacerun: yes">&nbsp; </span>Often take a hardware<br />
 exception.</font></li>
	<li class=MsoNormal<br />
 style="MARGIN: 0in 0in 0pt; tab-stops: list.5in; mso-list: l3 level1 lfo7"><font face=Tahoma size=2>Notify any attached debuggers, profilers, vectored<br />
 exception handlers and other interested parties.</font></li>
</ul>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>This is<br />
light years away from returning a -1 from your function call.<span style="mso-spacerun: yes">&nbsp; </span>Exceptions are inherently non-local, and<br />
if there’s an obvious and enduring trend for today’s architectures, it’s that<br />
you must remain local for good performance.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>Relative<br />
to straight-line local execution, exception performance will keep getting<br />
worse.<span style="mso-spacerun: yes">&nbsp; </span>Sure, we might dig into our<br />
current behavior and speed it up a little.<span style="mso-spacerun: yes">&nbsp;<br />
</span>But the trend will relentlessly make exceptions perform worse.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>How do I<br />
reconcile the trend to worse performance with our recommendation that managed<br />
code should use exceptions to communicate errors?<span style="mso-spacerun: yes">&nbsp; </span>By ensuring that error cases are<br />
exceedingly rare.<span style="mso-spacerun: yes">&nbsp; </span>We used to say<br />
that exceptions should be used for exceptional cases, but folks pushed back on<br />
that as tautological.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If your<br />
API fails in 10% of all calls, you better not use an exception.<span style="mso-spacerun: yes">&nbsp; </span>Instead, change the API so that it<br />
communicates its success or failure as part of the API (e.g. ‘bool<br />
TryParse(String s)’).<span style="mso-spacerun: yes">&nbsp; </span>Even if the<br />
API fails 1% of calls, this may be too high a rate for a service that’s heavily<br />
used in a server.<span style="mso-spacerun: yes">&nbsp; </span>If 1% of calls<br />
fail and we’re processing 1000 requests per second with 100 of these API calls<br />
per request, then we are throwing 1000 times a second.<span style="mso-spacerun: yes">&nbsp; </span>That’s a <i style="mso-bidi-font-style: normal">very</i> disturbing rate of exceptions.<span style="mso-spacerun: yes">&nbsp; </span>On the other hand, a 1% failure rate may<br />
be quite tolerable in a client scenario, if the exception occurs when a human<br />
user presses the wrong button.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma<br />
size=2>Sometimes you won’t know whether your API will be used in a client or a<br />
server.<span style="mso-spacerun: yes">&nbsp; </span>And it may be hard for you<br />
to predict failure rates when errors are triggered by bad data from the<br />
client.<span style="mso-spacerun: yes">&nbsp; </span>If you’ve provided a way<br />
for the client to check his data without triggering an exception (like the<br />
TryParse() example above) then you’ve done your part.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>As<br />
usual, there’s so much more to say.<span style="mso-spacerun: yes">&nbsp;<br />
</span>I still haven’t talked about unhandled exceptions.<span style="mso-spacerun: yes">&nbsp; </span>Or about undeniable exception<br />
propagation (Thread.Abort).<span style="mso-spacerun: yes">&nbsp; </span>Or how<br />
undeniable propagation interacts with propagation through unmanaged code via<br />
PInvoke, IJW or COM Interop.<span style="mso-spacerun: yes">&nbsp; </span>And I<br />
carefully avoided explaining why we didn’t follow our own rules when defining<br />
and using the Exception class hierarchy.<span style="mso-spacerun: yes">&nbsp;<br />
</span>And there’s plenty to say about our special treatment of<br />
OutOfMemoryException and StackOverflowException.</font></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><o :p><font face=Tahoma<br />
size=2>&nbsp;</font></o></p>
	<p class=MsoNormal style="MARGIN: 0in 0in 0pt"><font face=Tahoma size=2>If you<br />
are still reading and actually want to know more, perhaps you should just apply<br />
for a job on the CLR team.</font></p>
<img src="http://blogs.msdn.com/aggbug.aspx?PostID=51524" width="1" height="1"/><br />
<span style="font-size:8pt; font-style:italic">http://blogs.msdn.com/cbrumme/archive/2003/10/01/51524.aspx</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cahtter.blogsome.com/2008/03/24/the-exception-model/feed/</wfw:commentRss>
	</item>
	</channel>
</rss>
