You need to check the whole snippet here:
public static async Task Main()
{
var weatherForecast = new WeatherForecast
{
// ...
};
string fileName = "WeatherForecast.json";
using FileStream createStream = File.Create(fileName);
await JsonSerializer.SerializeAsync(createStream, weatherForecast);
await createStream.DisposeAsync();
Console.WriteLine(File.ReadAllText(fileName));
}
using
declaration will call Dispose
in generated finally block at the end of the current scope, the problem here is that the file is accessed before the end of the scope:
Console.WriteLine(File.ReadAllText(fileName));
So the await createStream.DisposeAsync();
is actually needed otherwise the file will not be accessible (or even if it would be - potentially not all data will be flushed).
In this concrete case switching to using
statement (the one with braces, also both using
statement and declaration actually support handling IAsyncDisposable
) would be cleaner and will make await createStream.DisposeAsync();
call redundant:
await using (FileStream createStream = File.Create(fileName))
{
await JsonSerializer.SerializeAsync(createStream, weatherForecast);
}
Console.WriteLine(File.ReadAllText(fileName));