'yield' enumerations that don't get 'finished' by caller - what happens
<p>suppose I have</p>

<pre><code>IEnumerable&lt;string&gt; Foo()
{
     try
     {

         /// open a network connection, start reading packets
         while(moredata)
         {
            yield return packet; 
        }
     }
     finally
      {
        // close connection 
      }
}
</code></pre>

<p>(Or maybe I did a 'using' - same thing). What happens if my caller goes</p>

<pre><code>var packet = Foo().First();
</code></pre>

<p>I am just left with a leaked connection. When does the finally get invoked? Or does the right thing always happen by magic</p>

<p><strong>edit with answer and thoughts</strong></p>

<p>My sample and other 'normal' (foreach, ..) calling patterns will work nicely because they dispose of the IEnumerable (actually the IEnumerator returned by GetEnumerator). I must therefore have a caller somewhere thats doing something funky (explicitly getting an enumerator and not disposing it or the like). I will have them shot</p>

<p><strong>the bad code</strong></p>

<p>I found a caller doing</p>

<pre><code>IEnumerator&lt;T&gt; enumerator = foo().GetEnumerator();
</code></pre>

<p>changed to </p>

<pre><code>using(IEnumerator&lt;T&gt; enumerator = foo().GetEnumerator())
</code></pre>