当使用内产量和QUOT;采用"声明中,什么时候发生的处置? [英] When using yield within a "using" statement, when does Dispose occur?

查看:150
本文介绍了当使用内产量和QUOT;采用"声明中,什么时候发生的处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于延期执行和数据的处置问题。

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>没有的可不会泄漏<案件(即某人unpugging机器)。

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;采用&QUOT;声明中,什么时候发生的处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆