Is there a better deterministic disposal pattern than nested "using"s?
Asked Answered
G

10

20

In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
    using (BufferedStream bs = new BufferedStream(fs))
    {
        using (StreamReader sr = new StreamReader(bs))
        {
            // use sr, and have everything cleaned up when done.
        }
    }
}

In C++, I'm used to being able to use destructors to do it like this:

{    
    FileStream fs("c:\file.txt", FileMode.Open);
    BufferedStream bs(fs);
    StreamReader sr(bs);
    // use sr, and have everything cleaned up when done.
}

Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?

Gratin answered 16/9, 2008 at 18:59 Comment(0)
S
41

You don't have to nest with multiple usings:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
    // all three get disposed when you're done
}

In .NET Core, there's a new using statement which allows you to dispense with the parentheses, and the disposal happens at the end of the current scope:

void MyMethod()
{
    using var fs = new FileStream("c:\file.txt", FileMode.Open);
    using var bs = new BufferedStream(fs);
    using var sr = new StreamReader(bs);
    // all three are disposed at the end of the method
}
Sclater answered 16/9, 2008 at 19:1 Comment(4)
That's just as nested - each successive using is treated as a one-line code block - think of an if statement, sans { }. All you've gained here is avoiding hitting the TAB key.Flossi
I agree with Greg Hurlman, it's a formatting trick: like if, while, etc, 'using' controls a single statement, but you normally use it with a block of statements.Earsplitting
Well, yes it's a formatting trick, but the point is that it's a helpful trick, and non-obvious to someone new to C#.Gratin
@GregHurlman, it's not "just as nested"; you'll find that if you autoformat in Visual Studio 2012, multiple one-line if statements get successively indented, but multiple one-line using statements as above don't.Sclater
H
8

You can put using statements together before the opening braces like so:

  using (StreamWriter w1 = File.CreateText("W1"))
  using (StreamWriter w2 = File.CreateText("W2"))
  {
      // code here
  }

http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx

Hissing answered 16/9, 2008 at 19:2 Comment(0)
M
3

You could use this syntax to condense things down a bit:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
}

This is one of those rare occasions where not using { } for all blocks makes sense IMHO.

Movement answered 16/9, 2008 at 19:2 Comment(0)
C
1

I have implemented solutions like Michael Meadows's before, but his StreamWrapper code doesn't take into account if the Dispose() methods called on the member variables throw an exception for one reason or another, the subsequent Dispose()es will not be called and resources could dangle. The safer way for that one to work is:

        var exceptions = new List<Exception>();

        try
        {
            this.sr.Dispose();
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }

        try
        {
            this.bs.Dispose();
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }

        try
        {
            this.fs.Dispose();
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }

        if (exceptions.Count > 0)
        {
            throw new AggregateException(exceptions);
        }
    }
Conciliate answered 16/9, 2008 at 20:25 Comment(1)
InnerException is a read-only property. How do you figure on writing it?Kirimia
F
0

Instead of nesting using statements, you can just write out the .Dispose calls manually - but you'll almost certainly miss one at some point.

Either run FxCop or something else that can make sure that all IDisposable-implementing type instances have a .Dispose() call, or deal with the nesting.

Flossi answered 16/9, 2008 at 19:1 Comment(0)
N
0

you can omit the curly braces, like:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
        // use sr, and have everything cleaned up when done.
}

or use the regular try finally approach:

FileStream fs = new FileStream("c:\file.txt", FileMode.Open);
BufferedStream bs = new BufferedStream(fs);
StreamReader sr = new StreamReader(bs);
try
{
        // use sr, and have everything cleaned up when done.
}finally{
   sr.Close(); // should be enough since you hand control to the reader
}
Northeaster answered 16/9, 2008 at 19:3 Comment(0)
H
0

This makes for a much larger net plus in lines of code, but a tangible gain in readability:

using (StreamWrapper wrapper = new StreamWrapper("c:\file.txt", FileMode.Open))
{
    // do stuff using wrapper.Reader
}

Where StreamWrapper is defined here:

private class StreamWrapper : IDisposable
{
    private readonly FileStream fs;
    private readonly BufferedStream bs;
    private readonly StreamReader sr;

    public StreamWrapper(string fileName, FileMode mode)
    {
        fs = new FileStream(fileName, mode);
        bs = new BufferedStream(fs);
        sr = new StreamReader(bs);
    }

    public StreamReader Reader
    {
        get { return sr; }
    }

    public void Dispose()
    {
        sr.Dispose();
        bs.Dispose();
        fs.Dispose();
    }
}

With some effort, StreamWrapper could be refactored to be more generic and reusable.

Haymo answered 16/9, 2008 at 19:8 Comment(0)
K
0

It should be noted that generally when creating stream based off another stream the new stream will close the one being passed in. So, to further reduce your example:

using (Stream Reader sr = new StreamReader( new BufferedStream( new FileStream("c:\file.txt", FileMode.Open))))
{
    // all three get disposed when you're done
}
Ketchum answered 16/9, 2008 at 23:32 Comment(1)
NOTE: exception safety FAIL. this will NOT close the FileStream if the BufferedStream constructor fails. using syntax is really tricky compares to C++ RAII.Ctenophore
C
0

for this example let us assume you have:

a file named 1.xml under c:\

a textbox named textBox1, with the multi-line properties set ON.

const string fname = @"c:\1.xml";

StreamReader sr=new StreamReader(new BufferedStream(new FileStream(fname,FileMode.Open,FileAccess.Read,FileShare.Delete)));
textBox1.Text = sr.ReadToEnd();
Combination answered 20/5, 2011 at 19:48 Comment(1)
No, you can't do that - if BufferedStream or StreamReader throw an exception during construction, the FileStream won't be disposed of until the GC gets around to cleaning up. You don't want to leave file handles floating around like that.Gratin
O
-1

The using statement is syntactic sugar that converts to:

   try
   {
      obj declaration
      ...
   }
   finally
   {
      obj.Dispose();
   }

You can explicitly call Dispose on your objects, but it won't be as safe, since if one of them throws an exception, the resources won't be freed properly.

Oxy answered 16/9, 2008 at 19:1 Comment(1)
NOTE: incorrect. the object initialization takes place OUTSIDE the try, even if there is more than one object. using(X a=f(),b=f()){g(a,b);} is the same as X a=f(); X b=f(); try{ g(a,b); } finally { b.Dispose(); a.Dispose(); there's a difference for exception safety.Ctenophore

© 2022 - 2024 — McMap. All rights reserved.