Skip to content

Commit 3491c96

Browse files
Added safe IDisposable cast to IEnumerator
The field _enumerator, being defined as an IEnumerator, does not directly suppoort IDisposable, however most of its implementations also inherit from IEnumerator<T>, which does. This could lead to potential memory leak problems if not handled with a Dispose call.
1 parent 01a71d9 commit 3491c96

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

src/MiniExcel/WriteAdapter/EnumerableWriteAdapter.cs

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,16 @@ public List<ExcelColumnInfo> GetColumns()
4545
_enumerator = _values.GetEnumerator();
4646
if (!_enumerator.MoveNext())
4747
{
48-
_empty = true;
49-
return null;
48+
try
49+
{
50+
_empty = true;
51+
return null;
52+
}
53+
finally
54+
{
55+
(_enumerator as IDisposable)?.Dispose();
56+
_enumerator = null;
57+
}
5058
}
5159
return CustomPropertyHelper.GetColumnInfoFromValue(_enumerator.Current, _configuration);
5260
}
@@ -58,20 +66,28 @@ public IEnumerable<IEnumerable<CellWriteInfo>> GetRows(List<ExcelColumnInfo> pro
5866
yield break;
5967
}
6068

61-
if (_enumerator is null)
69+
try
6270
{
63-
_enumerator = _values.GetEnumerator();
64-
if (!_enumerator.MoveNext())
71+
if (_enumerator is null)
6572
{
66-
yield break;
73+
_enumerator = _values.GetEnumerator();
74+
if (!_enumerator.MoveNext())
75+
{
76+
yield break;
77+
}
6778
}
68-
}
6979

70-
do
80+
do
81+
{
82+
cancellationToken.ThrowIfCancellationRequested();
83+
yield return GetRowValues(_enumerator.Current, props);
84+
} while (_enumerator.MoveNext());
85+
}
86+
finally
7187
{
72-
cancellationToken.ThrowIfCancellationRequested();
73-
yield return GetRowValues(_enumerator.Current, props);
74-
} while (_enumerator.MoveNext());
88+
(_enumerator as IDisposable)?.Dispose();
89+
_enumerator = null;
90+
}
7591
}
7692

7793

0 commit comments

Comments
 (0)