avoid ReadFile syscall if we know that there is nothing to read from file (#56387)
authorAdam Sitnik <adam.sitnik@gmail.com>
Tue, 27 Jul 2021 16:13:38 +0000 (18:13 +0200)
committerGitHub <noreply@github.com>
Tue, 27 Jul 2021 16:13:38 +0000 (18:13 +0200)
* 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>
src/libraries/System.Private.CoreLib/src/System/IO/Strategies/AsyncWindowsFileStreamStrategy.cs
src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs

index 0f59f6748a1a43cba85bbe1f63c26b8c1334cd72..13e6bd7b867c9dc18eb4ee50f09a9ebf6c3184f1 100644 (file)
@@ -50,6 +50,12 @@ namespace System.IO.Strategies
                 // 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);
index 7652fc768c1f35ca837e831047491e6d97ba6eba..c6115ef04dfa87733d4c09d2334d2acfa597ae8d 100644 (file)
@@ -115,7 +115,7 @@ namespace System.IO.Strategies
             }
         }
 
-        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