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

前端 未结 10 1696
难免孤独
难免孤独 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条回答
  •  萌比男神i
    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
    }
    

提交回复
热议问题