Bug in the File.ReadLines(..) method of the .net framework 4.0

后端 未结 7 1364
渐次进展
渐次进展 2021-01-11 16:31

This code :

IEnumerable lines = File.ReadLines(\"file path\");
foreach (var line in lines)
{
    Console.WriteLine(line); 
}
foreach (var line          


        
相关标签:
7条回答
  • 2021-01-11 16:46

    It's not a bug. File.ReadLines() uses lazy evaluation and it is not idempotent. That's why it's not safe to enumerate it twice in a row. Remember an IEnumerable represents a data source that can be enumerated, it does not state it is safe to be enumerated twice, although this might be unexpected since most people are used to using IEnumerable over idempotent collections.

    From the MSDN:

    The ReadLines(String, System) and ReadAllLines(String, System) methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array.Therefore, when you are working with very large files, ReadLines can be more efficient.

    Your findings via reflector are correct and verify this behavior. The implementation you provided avoids this unexpected behavior but makes still use of lazy evaluation.

    0 讨论(0)
提交回复
热议问题