Skip to content

Commit c81ca16

Browse files
avoid ReadFile syscall if we know that there is nothing to read from file (#56387)
* avoid ReadFile syscall if we know that there is nothing to read from file * Apply suggestions from code review Co-authored-by: Stephen Toub <[email protected]>
1 parent 72393ff commit c81ca16

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

src/libraries/System.Private.CoreLib/src/System/IO/Strategies/AsyncWindowsFileStreamStrategy.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ private unsafe ValueTask<int> ReadAsyncInternal(Memory<byte> destination, Cancel
5050
// touch the file pointer location at all. We will adjust it
5151
// ourselves, but only in memory. This isn't threadsafe.
5252
_filePosition += destination.Length;
53+
54+
// We know for sure that there is nothing to read, so we just return here and avoid a sys-call.
55+
if (destination.IsEmpty && LengthCachingSupported)
56+
{
57+
return ValueTask.FromResult(0);
58+
}
5359
}
5460

5561
(SafeFileHandle.OverlappedValueTaskSource? vts, int errorCode) = RandomAccess.QueueAsyncReadFile(_fileHandle, destination, positionBefore, cancellationToken);

src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ protected void UpdateLengthOnChangePosition()
115115
}
116116
}
117117

118-
private bool LengthCachingSupported => OperatingSystem.IsWindows() && _share <= FileShare.Read && !_exposedHandle;
118+
protected bool LengthCachingSupported => OperatingSystem.IsWindows() && _share <= FileShare.Read && !_exposedHandle;
119119

120120
/// <summary>Gets or sets the position within the current stream</summary>
121121
public sealed override long Position

0 commit comments

Comments
 (0)