VB.NET:关于“使用”的问题堵塞
考虑代码:
On Error Goto ErrorHandler
Using sr As StreamReader = New StreamReader(OpenFile)
str = sr.ReadToEnd
sr.Close()
End Using
Exit Sub
ErrorHandler:
如果 Using
块内出现错误,如何清理 sr
对象?
sr
对象不在 ErrHandler
的范围内,因此无法调用 sr.Close()。即使出现错误,Using
是否会自动阻止清理任何资源?
Consider the code:
On Error Goto ErrorHandler
Using sr As StreamReader = New StreamReader(OpenFile)
str = sr.ReadToEnd
sr.Close()
End Using
Exit Sub
ErrorHandler:
If there is an error inside the Using
block how do you clean up the sr
object?
The sr
object is not in scope in ErrHandler
so sr.Close() cannot be called. Does the Using
block cleanup any resources automatically even if there is an error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 codeka 所说,您不需要在 sr 上调用
Close
。它会自动调用,包括是否出现错误。使用using
语句可以提供与try ... finally ... end try
相同的功能。正如您在其他问题的答案中看到的那样,您不应该使用
On Error
等,只需执行以下操作:As codeka says, you don't need to call
Close
on sr. It'll called automatically, and that includes if there is an error. Using theusing
statement gives you the same functionality astry ... finally ... end try
.And as you see in the answers to your other question, you shouldn't be using
On Error
etc just do:是的,using 块会自动调用
IDisposable.Dispose
(对于StreamReader
来说,这与调用Close
相同),因此您无需执行任何操作要做的事情(这就是使用块的全部要点!)Yes, the using block will automatically call
IDisposable.Dispose
(which, for aStreamReader
is the same as callingClose
) so there's nothing you need to do (that's the whole point of using blocks!)这段代码:
实际上相当于:
请记住,
Finally
块中的代码将在方法返回之前始终执行(如果它抛出自己的异常,那么,那么你就会陷入一个受伤的世界)。因此,Using
块中的sr.Close
行是多余的(请注意,在使用Try
/的等效代码中没有必要) Final
因为sr.Close
将在Finally
中被调用,无论发生什么——是否抛出异常)。This code:
Is really equivalent to this:
Keep in mind that code within a
Finally
block will always execute before the method returns (if it throws an exception of its own, well, then you're in for a world of hurt). So thesr.Close
line you have within yourUsing
block is superfluous (notice it is unnecessary in the equivalent code usingTry
/Finally
sincesr.Close
will be called in theFinally
no matter what -- exception thrown or not).