I have a question regarding deferred execution and the disposing of data.
Consider the following example:
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++;
}
}
}
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?
break
when the counter hits two, just add aTake(2)
to the end ofParseFile
. – Quan