17 using System.Collections;
18 using System.Collections.Generic;
20 using System.Threading;
29 private int _disposed;
30 private int _createdEnumerator;
31 private readonly StreamReader _reader;
32 private readonly IDisposable[] _disposables;
41 _disposables = disposables;
46 _reader =
new StreamReader(stream);
57 _disposables = disposables;
66 if (Interlocked.CompareExchange(ref _createdEnumerator, 1, 0) == 1)
68 throw new InvalidOperationException(
"A StreamReaderEnumerable may only be enumerated once. Consider using memoization or materialization.");
71 return new Enumerator(
this);
77 IEnumerator IEnumerable.GetEnumerator()
86 if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 1)
91 _reader.DisposeSafely();
92 if (_disposables !=
null)
94 foreach (var disposable
in _disposables)
96 disposable.DisposeSafely();
109 private class Enumerator : IEnumerator<string>
113 public string Current {
get;
private set; }
115 object IEnumerator.Current => Current;
119 _enumerable = enumerable;
122 public bool MoveNext()
124 var line = _enumerable._reader.ReadLine();
136 if (!_enumerable._reader.BaseStream.CanSeek)
138 throw new InvalidOperationException(
"The underlying stream is unseekable");
141 _enumerable._reader.BaseStream.Seek(0, SeekOrigin.Begin);
146 _enumerable.Dispose();
151 _enumerable.Dispose();