Is there a better deterministic disposal pattern than nested “using”s?

前端 未结 10 1423
难免孤独
难免孤独 2021-02-18 18:23

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 furt

相关标签:
10条回答
  • 2021-02-18 18:50

    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();
    
    0 讨论(0)
  • 2021-02-18 18:50

    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.

    0 讨论(0)
  • 2021-02-18 18:55

    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
    }
    
    0 讨论(0)
  • 2021-02-18 18:57

    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.

    0 讨论(0)
提交回复
热议问题