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

<channel>
	<title>pc &#187; CLR</title>
	<atom:link href="http://projectcoho.com/?cat=4&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://projectcoho.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Sun, 22 Jan 2012 01:26:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Where Did My Object Go? Part 2</title>
		<link>http://projectcoho.com/?p=7</link>
		<comments>http://projectcoho.com/?p=7#comments</comments>
		<pubDate>Mon, 03 Dec 2007 20:18:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[Code Review]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=7</guid>
		<description><![CDATA[In Part 1 of this article I discussed the possibility of an object instance being collected before a method returns in this scenario:  new MyObject().LongRunningMethod(); as well as this scenario:  MyObject o = new MyObject(); o.LongRunningMethod(); Here we&#8217;ll discuss how &#8230; <a href="http://projectcoho.com/?p=7">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.codeneverwritten.com/2007/12/where-did-my-object-go-part-1.html" target="_blank">Part 1</a> of this article I discussed the possibility of an object instance being collected before a method returns in this scenario: </p>
<pre class="code">    <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>().LongRunningMethod();</pre>
<p>as well as this scenario: </p>
<pre class="code">    <span style="color: #2b91af;">MyObject</span> o = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>();    o.LongRunningMethod();</pre>
<p>Here we&#8217;ll discuss how this could become a problem. Frankly, it&#8217;s pretty easy to cause the problem, but I think it generally involves some ugliness on the part of software design or implementation, largely involving clean-up of fields when the instance is finalized. </p>
<h3>Don&#8217;t Try This at Home</h3>
<p>I don&#8217;t think it&#8217;s likely you&#8217;ll see a lot of code that does this, but here&#8217;s one way to run afoul of your object going way: export a reference to a field that the object cleans up when it&#8217;s finalized. You can export the reference, say, by making that field visible through a property. Exposing a field that you&#8217;re going to clean up in the finalizer would be an easy way to create a coupling between your object and other (arbitrary) client code that has no knowledge of your object&#8217;s life span. </p>
<h3>Call Stack Antics</h3>
<p>Another way to invoke the potential problem is to lose your &#8220;this&#8221; reference on the call stack. The code below manages to lose the &#8220;this&#8221; reference by passing a field to the helper method rather than allowing the helper to access the field directly via its own &#8220;this&#8221; reference. When the helper tries to access <span style="font-family: Courier New;">fs.Length</span> an <span style="font-family: Courier New;">ObjectDisposedException</span> is thrown. </p>
<p>Why does this throw? Well, the last live reference to the instance was lost when <span style="font-family: Courier New;">LongRunningMethod</span> passed <span style="font-family: Courier New;">_input</span> to <span style="font-family: Courier New;">Helper</span>. Essentially we&#8217;ve again exported the field value from the instance and no longer hold a reference to the instance, allowing the GC to finalize it. <span style="font-family: Courier New;">Helper</span> is left holding a reference to an object that has been finalized. </p>
<p><a href="http://11011.net/software/vspaste"></a><strong>Note:</strong> Again, you will not see this behavior in a debug build. When running code marked as &#8220;debug&#8221; the JITter <a href="http://blogs.msdn.com/yunjin/archive/2005/05/15/417569.aspx" target="_blank">extends the lifetime</a> of the local object to the end of the method. So you will not see this effect if you&#8217;ve compiled with the /debug flag. </p>
<pre class="code">    <span style="color: #0000ff;">using</span> System;    <span style="color: #0000ff;">using</span> System.IO;

    <span style="color: #008000;">// Ugliness ensues.
</span>    <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">MyUglyObject
</span>    {
        <span style="color: #0000ff;">public</span> MyUglyObject(<span style="color: #0000ff;">string</span> inputPath)
        {
            <span style="color: #008000;">// Real production code would likely not delete the file when done...
</span>            <span style="color: #008000;">// ...but this is a sample app.
</span>            _input = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">FileStream</span>(<span style="color: #2b91af;">Path</span>.GetTempFileName(), <span style="color: #2b91af;">FileMode</span>.Open, <span style="color: #2b91af;">FileAccess</span>.Read, <span style="color: #2b91af;">FileShare</span>.Read);
        }

        ~MyUglyObject()
        {
            <span style="color: #0000ff;">if</span> (_input != <span style="color: #0000ff;">null</span>)
            {
                _input.Close();
                _input = <span style="color: #0000ff;">null</span>;
            }
        }

        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> LongRunningMethod()
        {
            Helper(_input); <span style="color: #008000;">// Our last reference to 'this' (implicit).
</span>        }

        <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> Helper(<span style="color: #2b91af;">FileStream</span> fs)
        {
            <span style="color: #008000;">// A long-running method can easily experience a garbage collection
</span>            <span style="color: #008000;">// before returning. This one happens for force it to occur.
</span>            <span style="color: #2b91af;">GC</span>.Collect();
            <span style="color: #2b91af;">GC</span>.WaitForPendingFinalizers();

            <span style="color: #008000;">// Ka-boom!
</span>            <span style="color: #0000ff;">long</span> inputSize = fs.Length;
            <span style="color: #008000;">// ...
</span>        }

        <span style="color: #0000ff;">private</span> <span style="color: #2b91af;">FileStream</span> _input;
    }

    <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">Program
</span>    {
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Main(<span style="color: #0000ff;">string</span>[] args)
        {
            <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyUglyObject</span>(<span style="color: #a31515;">@"....readme.txt"</span>).LongRunningMethod();
        }
    }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h3>Can You See It?</h3>
<p>As you can see above it takes a bit of effort to cause the code to blow up. If <span style="font-family: Courier New;">Helper</span> had used <span style="font-family: Courier New;">_input.Length</span> instead of taking a parameter the problem would not exist. </p>
<p>But, what I find a bit creepy about the above code is that if <span style="font-family: Courier New;">Helper</span> were a static method it would seem respectable: </p>
<pre class="code">    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Helper(<span style="color: #2b91af;">FileStream</span> fs)
    {
        <span style="color: #008000;">// A long-running method can easily experience a garbage collection
</span>        <span style="color: #008000;">// before returning. This one happens for force it to occur.
</span>        <span style="color: #2b91af;">GC</span>.Collect();
        <span style="color: #2b91af;">GC</span>.WaitForPendingFinalizers();

        <span style="color: #008000;">// Ka-boom!
</span>        <span style="color: #0000ff;">long</span> inputSize = fs.Length;
        <span style="color: #008000;">// ...
</span>    }</pre>
<p><a href="http://11011.net/software/vspaste"></a>At first glance it now looks like helper is a normal static helper function, as is likely seen in code bases across the world. It doesn&#8217;t need a &#8220;this&#8221; reference, it takes a reference to the object it uses, everything appears fine on the surface. Would you see the &#8220;this&#8221; reference being lost by the code calling <span style="font-family: Courier New;">Helper</span> in a code review? I&#8217;m not so sure I would have until recently. </p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:5ab9e4f3-aaea-4ce5-83ea-be553bd2b340" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/Coding">Coding</a>, <a rel="tag" href="http://technorati.com/tags/Software%20Design">Software Design</a>, <a rel="tag" href="http://technorati.com/tags/CLR">CLR</a>, <a rel="tag" href="http://technorati.com/tags/C#">C#</a>, <a rel="tag" href="http://technorati.com/tags/Code%20Review">Code Review</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-4548100263884978316?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=7</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where Did My Object Go? Part 1</title>
		<link>http://projectcoho.com/?p=8</link>
		<comments>http://projectcoho.com/?p=8#comments</comments>
		<pubDate>Mon, 03 Dec 2007 19:14:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[Code Review]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=8</guid>
		<description><![CDATA[I ran across this scenario a few months ago and was just reminded of it. It takes a bit of an edge case to make it a problem, but it&#8217;s interesting all the same. There&#8217;s a regular idiom in C# &#8230; <a href="http://projectcoho.com/?p=8">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I ran across this scenario a few months ago and was just <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=362232#362232" target="_blank">reminded</a> of it. It takes a bit of an edge case to make it a problem, but it&#8217;s interesting all the same.</p>
<p>There&#8217;s a regular idiom in C# in which we call a method on an object instance that we&#8217;ve created inline:</p>
<pre class="code">    <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>().LongRunningMethod();</pre>
<p>There assumption may be an assumption that the lifetime of this instance of <span style="color: #2b91af;"><span style="font-family: Courier New;">MyObject</span></span> extends at least until <span style="font-family: Courier New;">LongRunningMethod</span> returns, but this isn&#8217;t necessarily true. This same assumption is often made about local references to objects:</p>
<pre class="code">    <span style="color: #2b91af;">MyObject</span> o = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>();    o.LongRunningMethod();</pre>
<p><a href="http://11011.net/software/vspaste"></a>However, in both these cases the object instance may be collected before <span style="font-family: Courier New;">LongRunningMethod</span> returns.</p>
<h3>Does this really happen?</h3>
<p>Yes, it can and does. The code below exercises this behavior. When you run it you will see the following output, indicating that the object was collected and finalized before <span style="font-family: Courier New;">LongRunningMethod</span> returns:</p>
<p><span style="font-family: Courier New; color: #008000;">    Using release build<br />
</span><span style="font-family: Courier New; color: #008000;">    Inline<br />
    Entering MyObject1.LongRunningMethod().<br />
    Finalizing in ~MyObject1().<br />
    Returning from MyObject1.LongRunningMethod(). </span><span style="font-family: Courier New; color: #008000;">    Local reference<br />
    Entering MyObject1.LongRunningMethod().<br />
    Finalizing in ~MyObject1().<br />
    Returning from MyObject1.LongRunningMethod().</span><strong>Note:</strong> You will not see this behavior in a debug build. When running code marked as &#8220;debug&#8221; the JITter <a href="http://blogs.msdn.com/yunjin/archive/2005/05/15/417569.aspx" target="_blank">extends the lifetime</a> of the local object to the end of the method. So you will <span style="text-decoration: underline;">not</span> see this effect if you&#8217;ve compiled with the /debug flag.</p>
<p>Note also that this article also assumes we&#8217;re using CLR 2.0. Future versions could obviously behavior differently.</p>
<p>Here&#8217;s the code. Just drop it into <span style="font-family: Courier New;">test.cs</span>, run <span style="font-family: Courier New;">csc test.cs</span>, and execute <span style="font-family: Courier New;">test.exe</span>.</p>
<pre class="code">    <span style="color: #0000ff;">using</span> System;

    <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">MyObject
</span>    {
        ~MyObject()
        {
            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Finalizing in ~MyObject1()."</span>);
        }

        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> LongRunningMethod()
        {
            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Entering MyObject1.LongRunningMethod()."</span>);

            <span style="color: #008000;">// A long-running method can easily experience a garbage collection
</span>            <span style="color: #008000;">// before returning. This one happens for force it to occur.
</span>            <span style="color: #2b91af;">GC</span>.Collect();
            <span style="color: #2b91af;">GC</span>.WaitForPendingFinalizers();

            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Returning from MyObject1.LongRunningMethod()."</span>);
        }
    }

    <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">Program
</span>    {
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Main(<span style="color: #0000ff;">string</span>[] args)
        {
<span style="color: #0000ff;">    #if</span> DEBUG
<span style="color: #808080;">            string build = "debug";
</span><span style="color: #0000ff;">    #else
</span>            <span style="color: #0000ff;">string</span> build = <span style="color: #a31515;">"release"</span>;
<span style="color: #0000ff;">    #endif
</span>            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Using {0} build"</span>, build);

            <span style="color: #008000;">// Try it both ways.

</span>            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Inline"</span>);
            <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>().LongRunningMethod();

            <span style="color: #2b91af;">Console</span>.WriteLine();
            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Local reference"</span>);
            <span style="color: #2b91af;">MyObject</span> o = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>();
            o.LongRunningMethod();
        }
    }</pre>
<h3>Is this a problem?</h3>
<p>Generally, I&#8217;d say it&#8217;s not a problem. Once it has begun execution, <span style="font-family: Courier New;">LongRunningMethod</span> doesn&#8217;t need the original object reference unless it&#8217;s making reference to that instance. In that case the GC won&#8217;t be able to collect the object.</p>
<p>I&#8217;ll discuss how to make it a problem in <a href="http://www.codeneverwritten.com/2007/12/where-did-my-object-go-part-2.html" target="_blank">Part 2</a> of this article.</p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:24332e3e-fe71-48b6-a509-a0c9cac22dcd" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/Coding">Coding</a>, <a rel="tag" href="http://technorati.com/tags/Software%20Design">Software Design</a>, <a rel="tag" href="http://technorati.com/tags/CLR">CLR</a>, <a rel="tag" href="http://technorati.com/tags/C#">C#</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-7952922260633718206?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=8</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
