Closed
Description
The current IEnumerable converters don't dispose of enumerators in certain scenaria where nested element converters throw exceptions. Reproducing test (using a few System.Text.Json.Tests components):
[Fact]
public static void WriteIEnumerableT_ElementSerializationThrows_DisposesEnumerators()
{
var items = new RefCountedList<IEnumerable<int>>(Enumerable.Repeat(ThrowingEnumerable(), 1));
Assert.Throws<DivideByZeroException>(() => JsonSerializer.Serialize(items.AsEnumerable()));
Assert.Equal(0, items.RefCount); // items.RefCount evaluates to 1
static IEnumerable<int> ThrowingEnumerable()
{
yield return 42;
throw new DivideByZeroException();
}
}
Note that #50778 makes changes to the serialization infrastructure to handle IEnumerator disposal in the async case, however changes on the individual converter level will still need to be made. cc @layomia @steveharter.