c#-3.0 - 关闭 FileStream 和将其设置为 null 有什么区别?

标签 c#-3.0

我有以下代码来读取单行并将其写入文本文件。我们可以在处理结束时将 null 分配给 reader 和 writer 对象吗?或者我应该调用 Close() 方法?谢谢。

FileInfo JFile = new FileInfo(@"C:\test.txt");
            using (FileStream JStream = JFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                StreamReader reader = null;
                StreamWriter writer = null;
                try
                {
                    int n;
                    reader = new StreamReader(JStream);
                    string line = reader.ReadLine();
                    int.TryParse(line, out n);

                    n = n + 1;

                    writer = new StreamWriter(JStream);
                    JStream.Seek(0, SeekOrigin.Begin);
                    writer.WriteLine(n);
                    writer.Flush();
                }
                catch (Exception x)
                {
                    string message = string.Format("Error while processing the file. {0}", x.Message);
                    System.Windows.Forms.MessageBox.Show(message);
                }

                reader = null;
                writer = null;
            }

最佳答案

关闭文件时需要发生某些事情。例如,当您的程序访问文件并创建 handle 时在上面。 .Close()-ing 流允许框架立即释放句柄和其他类似资源。

当您将其设置为 null 时,您将依赖垃圾收集器来为您执行此重要功能。 GC 现在可能会清理所有内容,也可能不会。你不知道它什么时候会发生。如果您的程序崩溃,它可能永远不会释放句柄。

完成后立即自行 .Close() 流总是一个好主意。

关于c#-3.0 - 关闭 FileStream 和将其设置为 null 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5915116/

相关文章:

asp.net - 如何提高 ASP.NET 网站的页面加载时间?

.net-3.5 - 派生类型不能隐式转换为基接口(interface)

c# - 如何打开 RadWindow

c# - 根据其他属性设置属性的方式

c# - 如何使用 C# 检查 XML 中具有特定属性值的元素

wpf - 如何动画窗口?

c# - “Could not find type” 在设计器中加载窗体时出错

c# - 将 DataBinder.Eval 与包含句点的索引器一起使用

inheritance - C# 从自身内部的嵌套类继承

c# - c=C# 中是否可以使用多个迭代器?