迭代器中的“finally”块

8
在C#迭代器块中,是否有一种方法可以提供一段代码块,在foreach结束时运行(自然结束或被打破),比如清理资源?
我想到的最好方法是使用using结构,这很好,但需要一个IDisposable类来进行清理。例如:
    public static IEnumerable<string> ReadLines(this Stream stream)
    {
        using (StreamReader rdr = new StreamReader(stream))
        {
            string txt = rdr.ReadLine();
            while (txt != null)
            {
                yield return txt;
                txt = rdr.ReadLine();
            }
            rdr.Close();
        }
    }
2个回答

6
try/finally结构在使用foreach或手动调用DisposeIEnumerator<T>中时能够正常工作。说实话,如果是为了清理资源,使用using语句可能是最好的方式 - 如果您正在使用需要清理但未实现IDisposable接口的资源,则这本身就是一个问题 :)。

在迭代器块中有一些限制,如Eric Lippert博客中所解释的,但在大多数情况下都非常完美地工作。

您可能会发现我的关于迭代器块实现的文章在翻译finally部分方面很有趣。


0

try/finally 在这种情况下起作用。

public static IEnumerable<string> ReadLines(this Stream stream)
{
    StreamReader rdr = new StreamReader(stream);

    try
    {
        string txt = rdr.ReadLine();
        while (txt != null)
        {
            yield return txt;
            txt = rdr.ReadLine();
        }
        rdr.Close();
    }
    finally
    {
        rdr.Dispose();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接