为什么我们在c#中使用streamreader前使用

时间:2011-07-12 11:07:30

标签: c# .net using

为什么我们在streamreader

之前使用c#之前使用
using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}

8 个答案:

答案 0 :(得分:10)

在处理一次性物体时,使用C#中的块非常方便。一次性对象是那些可以在调用dispose时显式释放它们使用的资源的对象。我们知道.Net垃圾收集是非确定性的,因此您无法预测对象何时会被垃圾收集。

阅读这篇文章了解更多详情:understanding ‘using’ block in C#

答案 1 :(得分:6)

因此,当您使用StreamReader时,它会被正确处理掉。此外,如果发生异常,using语句会在异常传播之前调用Dispose

答案 2 :(得分:6)

在使用实现using的对象(IDisposable执行)时使用StreamReader语法的好习惯,因为它确保了Dispose方法总是被调用,对象被妥善处理。

例如,在这种情况下,将在文件“ TestFile.txt ”上获取各种句柄/锁,这可能会阻止其他人写入或甚至读取此文件,直到流式读取器被丢弃为止或者过程结束。其他对象(例如数据库对象)可能会耗尽数据库连接或网络资源,因此您应该在使用完对象后立即处置对象 - 在执行此操作时,using语句只是一个简单而安全的模式。 / p>

在幕后发生的事情与此类似(reference):

StreamReader sr = new StreamReader("TestFile.txt");
try
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}
finally
{
    if (sr != null)
    {
        ((IDisposable)sr).Dispose();
    }
}

然而,使用声明比试图手动处理IDisposable更清晰(并且更不容易出错)。

答案 3 :(得分:3)

如果没有using,文件结束时就不会关闭。

答案 4 :(得分:3)

编译器将代码翻译为:

StreamReader sr = new StreamReader("TestFile.txt")
try
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}
finally
{
    sr.Dispose();
}

这确保无论发生什么,sr都得到妥善处理(清理)。每当创建一个实现IDisposable接口的对象时,最好将其包装在using构造中,以确保它被清理并尽快释放任何昂贵或稀缺的资源。

答案 5 :(得分:3)

在完成对象后,有时我们Dispose对象很重要。

using块中包装对象的构造意味着在大括号内的代码完成后,处理将自动处理。

如果StreamReader读取文本文件,这很重要,因为当StreamReader正在读取文件时系统会锁定该文件。释放锁允许其他进程修改或删除文件。

答案 6 :(得分:3)

using声明保证会调用Dispose()方法,Dispose()调用stream.Close()

答案 7 :(得分:2)

您不需要使用,但它是一种方便的方式来绝对确保对象被妥善处理。你可以不使用,只要你确定你总是在最后处置对象(using一个最终是正常的方式)。如果有特定原因希望进一步持久保存该对象,则可以执行此操作。

但是,如果您尝试执行此操作,可能会出现代码结构。在StreamReader语句中包含对iDisposible(以及其他using个对象)的使用有助于很好地构建代码。

相关问题