为什么我们在 C# 中将 using 放在 StreamReader 之前
为什么我们在c#
中把using放在streamreader
之前
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);
}
}
why do we put using before streamreader
in 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在处理一次性对象时,在 C# 中使用 block 非常方便。可处置对象是那些在调用处置时可以显式释放其使用的资源的对象。正如我们所知,.Net 垃圾收集是不确定的,因此您无法预测对象何时将被垃圾收集。
阅读这篇文章了解更多详细信息:理解 C# 中的“using”块
using block in C# comes very handly while dealing with disposable objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can’t predict when exactly the object will be garbage collected.
Read this post for more in details : understanding ‘using’ block in C#
这样,当您使用完 StreamReader 后,它就会被正确处理。此外,如果发生异常,
using
语句会在异常传播出去之前调用Dispose
。So that when you are done using
StreamReader
it is disposed of properly. Also, in the event of an exception, theusing
statement callsDispose
before the exception propagates out.每当您使用实现了 IDisposable 的对象(
StreamReader
就是这样做的)时,最好使用using
语法,因为它可以确保Dispose
方法总是被调用并且对象被正确处置。例如,在这种情况下,将在文件“TestFile.txt”上获得各种句柄/锁,这可能会阻止其他人写入甚至读取该文件,直到处理掉流读取器或进程结束。其他对象(例如数据库对象)可能会耗尽数据库连接或网络资源,因此您应该在使用完对象后立即丢弃它们 - using 语句只是执行此操作时遵循的一种简单且安全的模式。
在幕后发生的事情与此类似(参考):
但是using 语句比尝试手动处理
IDisposable
更简洁(并且更不容易出错)。Its good practice to use the
using
syntax whenever you are working with an object that implementsIDisposable
, (whichStreamReader
does) as it ensures that theDispose
method always gets called and the object is properly disposed of.For example in this case various handles / locks will be obtained on the file "TestFile.txt" that may prevent others from writing to or even reading this file until either the stream reader is disposed of or the process ends. Other objects (such as database objects) may use up database connections or network resources and so you should always dispose of objects as soon as you are done using them - the using statement is simply an easy and safe pattern to follow when doing this.
Under the covers whats happening is similar to this (reference):
However the using statement is much cleaner (and less error prone) than attempting to dispose of the
IDisposable
by hand.如果没有
using
,文件在完成时不会被关闭。Without
using
the file would not be closed when it was finished with.代码由编译器翻译为:
这确保无论发生什么,
sr
都得到正确处理(清理)。每当创建实现 IDisposable 接口的对象时,最佳实践是将其包装在 using 构造中,以确保它被清理并尽快释放任何昂贵或稀缺的资源尽可能。The code is translated by the compiler to:
This ensures that whatever happens,
sr
is properly disposed (cleaned up). Whenever an object is created that implements theIDisposable
interface it is best practice to wrap it in ausing
construct to ensure it is cleaned up and releases any expensive or scarce resources as quickly as possible.有时,在使用完对象后
Dispose
很重要。将对象的构造包装在
using
块中意味着一旦大括号内的代码完成,就会自动处理处理。对于 StreamReader 读取文本文件的情况,这一点很重要,因为在 StreamReader 读取文件时文件被系统锁定。释放锁允许其他进程修改或删除该文件。
Sometimes it is important that we
Dispose
of objects after we have finished with them.Wrapping the construction of an object in a
using
block means that the disposal is handled automatically as soon the code within the braces is completed.In the case of a
StreamReader
reading a text file, this is important as the file is locked by the system while the StreamReader is reading it. Releasing the lock allows other processes to modify or delete the file.using
语句保证调用Dispose()
方法,并且Dispose()
调用stream.Close()
using
statement guaranteed thatDispose()
method will be called, andDispose()
callsstream.Close()
您不需要使用 using,但这是绝对确定对象已正确处置的便捷方法。您可以在不使用 using 的情况下执行此操作,只要您确定始终在最后处理该对象(
using
a finally 是正常方式)。如果有特定原因想要进一步保留该对象,您可以这样做。但是,如果您尝试执行此操作,则您的代码结构可能存在问题。将
StreamReader
(和其他iDisposible
对象)的使用包含在using
语句中有助于更好地构建代码。You don't need to use using, but it is a convenient way of being absolutely sure that the object is properly disposed of. You can do this without using, as long as you are certain that you always dispose of the object at the end (
using
a finally is the normal way ). If there are specific reasons for wanting to persist the object further you can do this.However, there is probaly something with your code structure if you are trying to do this. Encasing your use of
StreamReader
( and otheriDisposible
objects ) in ausing
statement helps to structure your code well.