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

前端 未结 10 1303
难免孤独
难免孤独 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:36

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

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

    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.

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

    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

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

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

    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.

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