FileStream.Position updates after ReadAsync or WriteAsync completes
FileStream.Position is now updated after ReadAsync or WriteAsync completes.
Change description
In previous .NET versions on Windows, FileStream.Position was updated after the asynchronous read or write operation started. Starting in .NET 6, FileStream.Position is updated optimistically:
- After WriteAsync starts, but if the operation fails or is canceled, the position is corrected.
- When ReadAsync starts, but if the entire buffer isn't read, the position is corrected after the operation completes.
Version introduced
.NET 6
Reason for change
FileStream has never been thread-safe, but until .NET 6, .NET has tried to support multiple concurrent calls to its asynchronous methods (ReadAsync and WriteAsync) on Windows.
This change was introduced to allow for 100% asynchronous file I/O with FileStream and to fix the following issues:
- FileStream.FlushAsync ends up doing synchronous writes
- Win32 FileStream turns async reads into sync reads
Recommended action
If you rely on FileStream.Position being set before the read or write starts because your code performs parallel reads or writes, you should switch to use the System.IO.RandomAccess API instead. The RandomAccess API is designed for parallel file operations.
To enable the .NET 5 behavior in .NET 6, specify an
AppContext
switch or an environment variable. By setting the switch totrue
, you opt out of all performance improvements made toFileStream
in .NET 6.{ "configProperties": { "System.IO.UseNet5CompatFileStream": true } }
set DOTNET_SYSTEM_IO_USENET5COMPATFILESTREAM=1
Important
This switch is only available in .NET 6. It was removed in .NET 7.