Skip to content

Commit

Permalink
avoid ReadFile syscall if we know that there is nothing to read from …
Browse files Browse the repository at this point in the history
…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 <stoub@microsoft.com>
  • Loading branch information
adamsitnik and stephentoub committed Jul 27, 2021
1 parent 72393ff commit c81ca16
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ private unsafe ValueTask<int> ReadAsyncInternal(Memory<byte> destination, Cancel
// touch the file pointer location at all. We will adjust it
// ourselves, but only in memory. This isn't threadsafe.
_filePosition += destination.Length;

// We know for sure that there is nothing to read, so we just return here and avoid a sys-call.
if (destination.IsEmpty && LengthCachingSupported)
{
return ValueTask.FromResult(0);
}
}

(SafeFileHandle.OverlappedValueTaskSource? vts, int errorCode) = RandomAccess.QueueAsyncReadFile(_fileHandle, destination, positionBefore, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ protected void UpdateLengthOnChangePosition()
}
}

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

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

0 comments on commit c81ca16

Please sign in to comment.