问题描述
我有一个关于延期执行和数据的处置问题。
I have a question regarding deferred execution and the disposing of data.
请看下面的例子:
private IEnumerable<string> ParseFile(string fileName)
{
using(StreamReader sr = new StreamReader(fileName))
{
string line;
while((line = sr.ReadLine()) != null)
{
yield return line;
}
}
}
private void LineReader(string fileName)
{
int counter = 0;
foreach(string line in ParseFile(fileName))
{
if(counter == 2)
{
break; // will this cause a dispose on the StreamReader?
} else
{
Console.WriteLine(line);
counter++;
}
}
}
请问破
声明立即引起 ParseFile
读者处置或仍然在上下文中考虑,并会锁定该文件打开,直到程序本身封闭?
Will the break
statement immediately cause the reader in ParseFile
to dispose or is it still considered in context and will lock the file open until the program itself is closed?
推荐答案
因此,我们必须要在几个不同的问题在这里。
So we have several separate issues going on here.
首先,对付迭代器块中使用
。 的IEnumerator
扩展的IDisposable
。产生迭代器块中的代码实际上是足够强大的,任何的try / finally块(A 使用了
尝试/终于
结果>创建块)导致的内容最后
块被称为枚举器的的Dispose
方法,如果它尚未被调用。所以只要枚举配置,也不会泄漏的StreamReader
。
First off, dealing with the using
in the iterator block. IEnumerator
extends IDisposable
. The code that generates iterator blocks is actually robust enough that any try/finally blocks (a using
results in a try/finally
block being created) results in the contents of the finally
block being called in the Dispose
method of the enumerator, if it wasn't already called. So as long as the enumerator is disposed, it won't leak the StreamReader
.
所以,现在我们扪心自问如果枚举器配置。所有的foreach
语句将调用的Dispose
的枚举(它应该实现的IDisposable
)。他们这样做,即使你退出使用破
或收益
语句,以及当它正常完成的。
So now we ask ourselves if the enumerator is disposed. All foreach
statements will call Dispose
on the enumerator (should it implement IDisposable
). They do so even if you exit using a break
or return
statement, as well as when it finishes normally.
所以,你可以肯定的是在所有情况下的资源不被泄露,除非在那里EM>没有的可不会泄漏
So you can be sure that under all circumstances the resource won't be leaked, barring the cases where nothing can be prevented from leaking (i.e. someone unpugging the machine).
这篇关于当使用内产量和QUOT;采用"声明中,什么时候发生的处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!