What happens when calling code exits prior to completing enumeration of a IEnumerable that is yield returning.
A simplified example:
public void HandleData()
{
int count = 0;
foreach (var datum in GetFileData())
{
//handle datum
if (++count > 10)
{
break;//early exit
}
}
}
public static IEnumerable<string> GetFileData()
{
using (StreamReader sr = _file.BuildStreamer())
{
string line = String.Empty;
while ((line = sr.ReadLine()) != null)
{
yield return line;
}
}
}
In this case it seems quite important that the StreamReader is closed in a timely manner. Is there a pattern needed to handle this scenario?