<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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>assafeenumerable &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/assafeenumerable/</link>
	<description>Feed of posts on WordPress.com tagged "assafeenumerable"</description>
	<pubDate>Sun, 03 Jan 2010 14:58:57 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Using IDisposables with LINQ]]></title>
<link>http://solutionizing.net/2009/07/23/using-idisposables-with-linq/</link>
<pubDate>Thu, 23 Jul 2009 08:28:29 +0000</pubDate>
<dc:creator>Keith Dahlby</dc:creator>
<guid>http://solutionizing.net/2009/07/23/using-idisposables-with-linq/</guid>
<description><![CDATA[Objects that implement IDisposable are everywhere. The interface even gets its own language features]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Objects that implement <code>IDisposable</code> are everywhere. The interface even gets its own language features (<a title="using Statement (C# Reference)" href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx">C#</a>, <a title="Using Statement (Visual Basic)" href="http://msdn.microsoft.com/en-us/library/htd05whh.aspx">VB</a>, <a title="Resource Management (F#)" href="http://msdn.microsoft.com/en-us/library/dd233240(VS.100).aspx">F#</a>). However, LINQ throws a few wrenches into things:</p>
<ol>
<li>LINQ&#8217;s query syntax depends on expressions; <code>using</code> blocks are statements.</li>
<li>When querying a sequence of <code>IDisposable</code> objects, there&#8217;s no easy way to ensure disposal after each element has been consumed.</li>
<li>Returning deferred queries from within a <code>using</code> statement is often desired, but fails spectacularly.</li>
</ol>
<p>There are possible work-arounds for each issue&#8230;</p>
<ol>
<li>Put the using statement in a method (named or anonymous) that is called from the query. See also: <a href="http://solutionizing.net/2009/02/20/thinking-functional-using/">Thinking Functional: Using</a>.</li>
<li>Use a method that creates a dispose-safe iterator of the sequence, like <a title="LINQ for SPWebCollection Revisited: AsSafeEnumerable" href="http://solutionizing.net/2009/01/05/linq-for-spwebcollection-revisited-assafeenumerable/">AsSafeEnumerable()</a>.</li>
<li>Refactor the method to inject the <code>IDisposable</code> dependency, as shown in the first part of Marc&#8217;s answer <a title="How does LINQ defer execution when in a using statement" href="http://stackoverflow.com/questions/456691/how-does-linq-defer-execution-when-in-a-using-statement/456698#456698">here</a>.</li>
</ol>
<p>But, as you might have guessed, I would like to propose a better solution. The code is really complex, so bear with me:</p>
<pre class="code">public static IEnumerable&#60;T&#62; Use&#60;T&#62;(this T obj) where T : IDisposable
{
    try
    {
        yield return obj;
    }
    finally
    {
        if (obj != null)
            obj.Dispose();
    }
}</pre>
<p>That&#8217;s it. We&#8217;re turning our <code>IDisposable</code> object into a single-element sequence. The trick is that the C# compiler will build an iterator for us that properly handles the <code>finally</code> clause, ensuring that our object will be disposed. It might be helpful to set a breakpoint on the <code>finally</code> clause to get a better idea what&#8217;s happening.</p>
<p>So how can this simple method solve all our problems? First up: &#8220;using&#8221; a <code>FileStream</code> object created in a LINQ query:</p>
<pre>var lengths = from path in myFiles
              from fs in File.OpenRead(path).Use()
              select new { path, fs.Length };</pre>
<p>Since the result of <code>Use()</code> is a single-element sequence, we can think of <code>from fs in something.Use()</code> as an assignment of that single value, <code>something</code>, to <code>fs</code>. In fact, it&#8217;s really quite similar to an F# <code>use</code> binding in that it will automatically clean itself up when it goes out of scope (by its enumerator calling <code>MoveNext()</code>).</p>
<p>Next, disposing elements from a collection. I&#8217;ll use the same SharePoint problem that <code>AsSafeEnumerable()</code> solves:</p>
<pre>var webs = from notDisposed in site.AllWebs
           from web in notDisposed.Use()
           select web.Title;</pre>
<p>I find this syntax rather clumsy compared with <code>AsSafeEnumerable()</code>, but it&#8217;s there if you need it.</p>
<p>Finally, let&#8217;s defer disposal of a LINQ to SQL <code>DataContext</code> until after the deferred query is executed, as an answer to the <a title="How does LINQ defer execution when in a using statement" href="http://stackoverflow.com/questions/456691/how-does-linq-defer-execution-when-in-a-using-statement">previously-linked Stack Overflow question</a>:</p>
<pre>IQueryable&#60;MyType&#62; MyFunc(string myValue)
{
    return from dc in new MyDataContext().Use()
           from row in dc.MyTable
           where row.MyField == myValue
           select row;
}

void UsingFunc()
{
    var result = MyFunc("MyValue").OrderBy(row =&#62; row.SortOrder);
    foreach(var row in result)
    {
        //Do something
    }
}</pre>
<p>The result of <code>MyFunc</code> now owns its destiny completely. It doesn&#8217;t depend on some potentially disposed <code>DataContext</code> &#8211; it just creates one that it will dispose when it&#8217;s done. There are probably situations where you would want to share a <code>DataContext</code> rather than create one on demand (I don&#8217;t use LINQ to SQL, I just blog about it), but again it&#8217;s there if you need it.</p>
<p>I&#8217;ve only started using this approach recently, so if you have any problems with it please share.</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
