Skip to content

Commit

Permalink
Fix length caching
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub committed Jul 7, 2021
1 parent 84502ff commit b3a6212
Showing 1 changed file with 9 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal abstract class OSFileStreamStrategy : FileStreamStrategy

protected long _filePosition;
private long _appendStart; // When appending, prevent overwriting file.
private long _length = -1; // When the file is locked for writes (_share <= FileShare.Read) cache file length in-memory, negative means that hasn't been fetched.
private long _length = -1; // When the file is locked for writes on Windows (_share <= FileShare.Read) cache file length in-memory, negative means that hasn't been fetched.
private bool _exposedHandle; // created from handle, or SafeFileHandle was used and the handle got exposed

internal OSFileStreamStrategy(SafeFileHandle handle, FileAccess access, FileShare share)
Expand Down Expand Up @@ -84,7 +84,7 @@ public unsafe sealed override long Length
{
get
{
if (!OperatingSystem.IsWindows() || _share > FileShare.Read || _exposedHandle)
if (!LengthCachingSupported)
{
return RandomAccess.GetFileLength(_fileHandle);
}
Expand All @@ -105,7 +105,7 @@ protected void UpdateLengthOnChangePosition()
{
// Do not update the cached length if the file is not locked
// or if the length hasn't been fetched.
if (!OperatingSystem.IsWindows() || _share > FileShare.Read || _length < 0 || _exposedHandle)
if (!LengthCachingSupported || _length < 0)
{
Debug.Assert(_length < 0);
return;
Expand All @@ -117,6 +117,8 @@ protected void UpdateLengthOnChangePosition()
}
}

private 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 Expand Up @@ -235,7 +237,10 @@ protected unsafe void SetLengthCore(long value)
Debug.Assert(value >= 0, "value >= 0");

FileStreamHelpers.SetFileLength(_fileHandle, value);
_length = value;
if (LengthCachingSupported)
{
_length = value;
}

if (_filePosition > value)
{
Expand Down

0 comments on commit b3a6212

Please sign in to comment.