C
C#2y ago
Ploxi

❔ [System.Text.Json] When to close the stream

I have a very large json file (500 mb or more), so naturally i would use System.Text.Json in combination with IAsyncEnumerable<FileMetaDataDto>. Now i want to open a stream to a file using the following:
public static async Task<T?> ReadAsJson<T>(this IContentProvider contentProvider, Uri uri, JsonSerializerOptions? options = null)
{
using var stream = await contentProvider.OpenContentStream(uri);
return await JsonSerializer.DeserializeAsync<T>(stream, options);
}
public static async Task<T?> ReadAsJson<T>(this IContentProvider contentProvider, Uri uri, JsonSerializerOptions? options = null)
{
using var stream = await contentProvider.OpenContentStream(uri);
return await JsonSerializer.DeserializeAsync<T>(stream, options);
}
But what if the serializer needs the stream afterwards? If i leave it open, the stream would be dangling in limbo until the GC decides that it really wouldnt neeed that referencing memory anymore....
1 Reply
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.