Skip to content

Fix TextReader.ReadAsync(Memory<char>) dropping data for non array-backed memory - #644

Merged
SimonCropp merged 1 commit into
mainfrom
fix/textreader-readasync-memory
Oct 11, 2026
Merged

SimonCropp merged 1 commit into
mainfrom
fix/textreader-readasync-memory

Conversation

@SimonCropp

Copy link
Copy Markdown
Owner

Bug

TextReader.ReadAsync(Memory<char>, CancellationToken) fell back to buffer.ToArray() when the memory was not array-backed (MemoryMarshal.TryGetArray returns false, e.g. a custom MemoryManager<char> or native memory). The read went into that temporary copy and was never copied back, so the caller's buffer stayed untouched while the returned count said chars had been read.

Fix

Same approach as the BCL: rent an array from ArrayPool<char>.Shared, read into it, copy the chars read into the destination memory, and return the array. The array is only returned to the pool once the underlying read has completed, since a cancellation via WaitAsync can leave the read in flight. The array-backed path is unchanged.

Test

TextReader_ReadAsync_Memory_NotArrayBacked reads into a slice of a MemoryManager<char> that does not override TryGetArray and checks the destination contents. Fails on net48 before the fix; passes on net48 and on net10.0 (BCL).

@SimonCropp SimonCropp added this to the 11.4.4 milestone Oct 11, 2026
@SimonCropp
SimonCropp merged commit d93a52c into main Oct 11, 2026
5 checks passed
@SimonCropp
SimonCropp deleted the fix/textreader-readasync-memory branch October 11, 2026 22:11
This was referenced Oct 12, 2026
This was referenced Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant