<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Dan Crevier's Blog : .Net development</title><link>http://blogs.msdn.com/dancre/archive/tags/.Net+development/default.aspx</link><description>Tags: .Net development</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Implications of the just in time nature of LINQ</title><link>http://blogs.msdn.com/dancre/archive/2008/03/25/implications-of-the-just-in-time-nature-of-linq.aspx</link><pubDate>Wed, 26 Mar 2008 05:30:56 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8337025</guid><dc:creator>dancre</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/dancre/comments/8337025.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dancre/commentrss.aspx?PostID=8337025</wfw:commentRss><description>&lt;p&gt;I love LINQ! I’ve found that much of the code I write involves manipulating collections in ways that can be very naturally expressed in LINQ. One interesting aspect of LINQ is that things are evaluated just in time as you enumerate over them. This can have a few unexpected consequences. Here are a couple of examples. Take the following test class:&lt;/p&gt;&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Test
        {
            &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Value { get; set; }
        }
&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;p&gt;Now, think about the following code:&lt;/p&gt;&lt;pre class="csharpcode"&gt;            IEnumerable&amp;lt;Test&amp;gt; tests = Enumerable.Range(1, 3).Select(i =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Test() { Value = i });

            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (Test test &lt;span class="kwrd"&gt;in&lt;/span&gt; tests)
            {
                test.Value += 100;
            }

            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (Test test &lt;span class="kwrd"&gt;in&lt;/span&gt; tests)
            {
                Console.WriteLine(test.Value);
            }
&lt;/pre&gt;
&lt;p&gt;For those not familiar with LINQ, the Enumerable.Range(1, 3) creates an IEumerable that ranges from 1 to 3, and then the Select creates new Test objects with a Value equal to the current value, meaning the overall expression creates Tests with values that range from 1 to 3. So, what does this output? You might expect 101, 102, and 103 because the first foreach increments the values. However, it prints 1, 2, 3. The reason is that foreach calls tests.GetEnumerator which runs through the process of creating Test objects as MoveNext/Current is called through the foreach loop. So, the first time we go though the loop it creates 3 Test objects and we increment the value. However, those Test objects are just returned by the enumerator and don’t get stored anywhere. The second time we go through the loop we create 3 new Test objects with values 1-3. One way to get the expected behavior would be to replace the first line with:&lt;/p&gt;&lt;pre class="csharpcode"&gt;            List&amp;lt;Test&amp;gt; tests = Enumerable.Range(1, 3).Select(i =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Test() { Value = i }).ToList();&lt;/pre&gt;
&lt;p&gt;This creates a list with the Test values once, and then the foreach statements will enumerate the same set of Test values in that list.&lt;/p&gt;
&lt;p&gt;Another gotcha of the just in time evaluation is that values in the lambda functions are evaluated at the time of enumeration. So, in the following example:&lt;/p&gt;&lt;pre class="csharpcode"&gt;            &lt;span class="kwrd"&gt;int&lt;/span&gt; x = 0;

            tests = Enumerable.Range(1, 3).Select(i =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Test() { Value = x + i });

            x = 100;

            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (Test test &lt;span class="kwrd"&gt;in&lt;/span&gt; tests)
            {
                Console.WriteLine(test.Value);
            }&lt;/pre&gt;
&lt;p&gt;You get 101, 102, and 103 output. That’s because the “x + i” expression is evaluated after x is set to 100. This sort of issue is more subtle when you return a LINQ expression from a function. Who knows when that will be evaluated and what will change by then. Using ToList() is a reasonable way to force the evaluation time.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8337025" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dancre/archive/tags/.Net+development/default.aspx">.Net development</category></item><item><title>Yield and usings - your Dispose may not be called!</title><link>http://blogs.msdn.com/dancre/archive/2008/03/14/yield-and-usings-your-dispose-may-not-be-called.aspx</link><pubDate>Sat, 15 Mar 2008 07:08:04 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8218319</guid><dc:creator>dancre</dc:creator><slash:comments>10</slash:comments><comments>http://blogs.msdn.com/dancre/comments/8218319.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dancre/commentrss.aspx?PostID=8218319</wfw:commentRss><description>&lt;p&gt;We ran into an interesting bug recently where a resource was being leaked because we weren't disposing of an IDisposable in some cases. Before I go any further I should state that the root bug is that the IDisposable hanging onto the resource should have implemented a finalizer, or even better, used &lt;a href="http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx"&gt;SafeHandle&lt;/a&gt;. However it wasn't our code.&lt;/p&gt; &lt;p&gt;We tracked down the bug to some code that looked like:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Foo&amp;gt; MyEnumerable()
    {
        &lt;span class="kwrd"&gt;using&lt;/span&gt; (&lt;span class="kwrd"&gt;new&lt;/span&gt; MyDisposable())
        {
            &lt;span class="rem"&gt;// code that calls yield&lt;/span&gt;
        }
    }&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;p&gt;Then, someone called MyEnumerable().GetEnumerator().MoveNext() without disposing it or wrapping it in a foreach. The result was that Dispose was never called on the disposable. I usually think of using guaranteeing that Dispose() gets called, except in extreme cases like thread abort exceptions. It sparked my curiosity to dig and figure out how this all works.&lt;/p&gt;
&lt;p&gt;First, a couple of words about Enumerables, Enumerators and yield. An IEnumerator provides a simple way to iterate through a collection, using MoveNext() to advance to the next element, and a property Current to get the value at the current position. MoveNext() returns false at the end of the collection. An IEnumerable is simply an object you can call GetEnumerator() on to get an IEnumerator you can use to enumerate it (for example, collections are IEnumerables).&lt;/p&gt;
&lt;p&gt;The yield keyword is a handy way to implement an IEnumerable that exposes the result of a series of calculations or operations in such a way that you can write serial code. I could spend a whole post on how cool yield is, but you can find that elsewhere. For a cool example, you can see the &lt;a href="http://www.differentpla.net/content/2007/06/generating-the-fibonacci-sequence-by-using-the-yield-keyword-non-recursively"&gt;Fibonacci series implemented using yield&lt;/a&gt;. Note: yield is not a feature of the CLR, it's magical syntactic sugar provided by C# 2.0.&lt;/p&gt;
&lt;p&gt;Let's take a simple example:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;class&lt;/span&gt; MyDisposable : IDisposable
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Dispose()
        {
            Console.WriteLine(&lt;span class="str"&gt;"Disposed"&lt;/span&gt;);
        }
    }&lt;/pre&gt;
&lt;p&gt;and the function:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; MyEnumerable()
    {
        &lt;span class="kwrd"&gt;using&lt;/span&gt; (&lt;span class="kwrd"&gt;new&lt;/span&gt; MyDisposable())
        {
            &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; 1;
            &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; 2;
        }
        Console.WriteLine(&lt;span class="str"&gt;"complete"&lt;/span&gt;);
    }&lt;/pre&gt;
&lt;p&gt;If you walk the collection with the following code:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    IEnumerator&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; enumerator = MyEnumerable().GetEnumerator();
    &lt;span class="kwrd"&gt;while&lt;/span&gt; (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
&lt;/pre&gt;
&lt;p&gt;It will print "1", "2", "Disposed", "complete". But, how does it work? If you were to implement this without yield, you'd probably have to create a gnarly state machine, with some special cases for cleanup. Well, that's exactly what the C# compiler does for you!&lt;/p&gt;
&lt;p&gt;Using &lt;a href="http://www.aisto.com/roeder/dotnet/"&gt;.NET Reflector&lt;/a&gt;, we can see what code is generated. The MyEnumerable() function returns a new instance of a compiler generated class. Leaving out some of the details, the core of MoveNext() looks like:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;switch&lt;/span&gt; (&lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state)
    {
        &lt;span class="kwrd"&gt;case&lt;/span&gt; 0:
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state = -1;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;7__wrap1 = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyDisposable();
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state = 1;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;2__current = 1;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state = 2;
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;

        &lt;span class="kwrd"&gt;case&lt;/span&gt; 2:
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state = 1;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;2__current = 2;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state = 3;
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;

        &lt;span class="kwrd"&gt;case&lt;/span&gt; 3:
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state = 1;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;m__Finally2();
            Console.WriteLine(&lt;span class="str"&gt;"complete"&lt;/span&gt;);
            &lt;span class="kwrd"&gt;break&lt;/span&gt;;
    }
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;false&lt;/span&gt;;&lt;/pre&gt;
&lt;p&gt;With:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; &amp;lt;&amp;gt;m__Finally2()
    {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;1__state = -1;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;7__wrap1 != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
        {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;7__wrap1.Dispose();
        }
    }&lt;/pre&gt;
&lt;p&gt;So, if you walk through the states, you can see in case 0, it creates the MyDisposable, sets current to 1 and returns true. When it's called again in state 2, it sets current to 2 and returns true. When it's called a third time, it calls the finally function that disposes of the MyDisposable and then writes out "complete".&lt;/p&gt;
&lt;p&gt;But, what happens in a partial enumeration? If you use foreach, like:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i &lt;span class="kwrd"&gt;in&lt;/span&gt; MyEnumerable())
    {
        Console.WriteLine(i);
        &lt;span class="kwrd"&gt;break&lt;/span&gt;;
    }&lt;/pre&gt;
&lt;p&gt;You might not expect it to call dispose. But, what it outputs is "1", "Disposed". The reason that this works is that the generated IEnumerator class also implements IDisposable where Dispose() calls &amp;lt;&amp;gt;m__Finally2(). And, foreach calls Dispose on its enumerator if it is an IDisposable.&lt;/p&gt;
&lt;p&gt;However, in the case of our bug, we weren't using a foreach, we were just using MoveNext/Current directly without enumerating through the entire list. In this case, the MyDisposable is never disposed, even when GC takes place. Is this a bug? I've gone back in forth in my mind. On the one hand, the Enumerable code has a using, and that's supposed to clean things up! The compiler could have implemented a finalizer for the temporary class to clean up. On the other hand, the IEnumerator it generated was an IDisposable, which we failed to dispose. I tend to land on the side that this isn't a bug (and I bet the C# team agrees). If you have something that's holding onto a critical resource, you should implement a finalizer or use a SafeHandle and not rely on Dispose being called. However, I did find it a bit surprising. Now I know!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8218319" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dancre/archive/tags/.Net+development/default.aspx">.Net development</category></item></channel></rss>