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

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

提交回复
热议问题