简体   繁体   English

Visual C# 何时需要 Close() 和 Dispose()?

[英]Visual C# When are Close() and Dispose() Needed?

I am new to Visual C# and don't understand when I need to use the Close() and Dispose() methods on FileStream and StreamReader objects.我是 Visual C# 的新手,不明白何时需要对 FileStream 和 StreamReader 对象使用 Close() 和 Dispose() 方法。 In the code snippet below, I open a file, read the first line, and validate that it is what is expected.在下面的代码片段中,我打开一个文件,读取第一行,并验证它是否符合预期。 Do I need all of the Close() and Dispose() calls shown?我需要显示所有的 Close() 和 Dispose() 调用吗? If not, when are they needed?如果没有,什么时候需要它们? Thank you!谢谢!

        FileStream fs = null;
        StreamReader sr = null;

        try
        {
            fs = new FileStream(txtMstrFile.Text, FileMode.Open, FileAccess.Read);
            using (sr = new StreamReader(fs))
            {
                if (String.IsNullOrEmpty(sLine = sr.ReadLine()))
                {
                    MessageBox.Show(Path.GetFileName(txtMstrFile.Text) + " is an empty file.", "Empty Master File", MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    sr.Close();
                    fs.Close();
                    fs.Dispose();
                    return;
                }
                if(!String.Equals(sLine, "Master File"))
                {
                    MessageBox.Show(Path.GetFileName(txtMstrFile.Text) + " has an invalid format.", "Master File is Invalid", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    sr.Close();
                    fs.Close();
                    fs.Dispose();
                    return;
                }
        // Code to process sLine here
                sr.Close();
            }
            fs.Close();
            fs.Dispose();
        }
        catch (IOException ex)
        {
            MessageBox.Show(Path.GetFileName(txtMstrFile.Text) + "\r\n" + ex.ToString(), "File Access Error", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
            sr.Close();
            fs.Close();
            fs.Dispose();
            return;
        }
        sr.Close();
        fs.Close();
        fs.Dispose();

Explicit Dispose() and Close() are rare avises in the typical code: using will do it for you:显式Dispose()Close()是典型代码中的罕见建议: using将为您完成:

   try {
     using (var sr = new StreamReader(new FileStream(txtMstrFile.Text, 
                                                     FileMode.Open, 
                                                     FileAccess.Read))) {
       string sLine = sr.ReadLine(); 

       if (String.IsNullOrEmpty(sLine)) {
         MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} is an empty file.", 
                          "Empty Master File", 
                           MessageBoxButtons.OK,
                           MessageBoxIcon.Information);

         return;
       }
     
       if (!String.Equals(sLine, "Master File")) {
         MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} has an invalid format.", 
                          "Empty Master File", 
                           MessageBoxButtons.OK,
                           MessageBoxIcon.Information);

         return;
       }  
     }  
   }
   catch (IOException ex) {
     MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)}\r\n{ex}", 
                      "File Access Error", 
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);

     return;
   }   

Please, don't concatenate string when creating messages, string interpolation : $"... " often is much more readable .请不要在创建消息时连接字符串,字符串插值$"... "通常更具可读性

Edit: You can totally get rid of Stream s and StreamReader s:编辑:您可以完全摆脱StreamStreamReader

   try {
     // That's enough to read the 1st file's line
     string sLine = File.ReadLines(txtMstrFile.Text).First();

     if (String.IsNullOrEmpty(sLine)) {
       MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} is an empty file.", 
                        "Empty Master File", 
                         MessageBoxButtons.OK,
                         MessageBoxIcon.Information);

       return;
     }
     
     if (!String.Equals(sLine, "Master File")) {
       MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)} has an invalid format.", 
                        "Empty Master File", 
                         MessageBoxButtons.OK,
                         MessageBoxIcon.Information);

       return;
     }
   }
   catch (IOException ex) {
     MessageBox.Show($"{Path.GetFileName(txtMstrFile.Text)}\r\n{ex}", 
                      "File Access Error", 
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);

     return;
   } 

Some computer languages leave memory management to the programmer so freeing up memory that is no longer required is known as garbage collection.一些计算机语言将 memory 管理留给程序员,因此释放不再需要的 memory 称为垃圾回收。 Dispose is the programmer's way of saying "clean up now". Dispose 是程序员说“立即清理”的方式。 Close is for closing things like connections to databases. Close 用于关闭诸如与数据库的连接之类的东西。 Close says "write any unwritten data to the file now" and is a safety measure that ensures that your file data is saved if your computer crash.关闭表示“现在将任何未写入的数据写入文件”,这是一种安全措施,可确保在计算机崩溃时保存文件数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM