Prefer the memory-based overloads of ReadAsync/WriteAsync methods in stream-based classes
Prefer the memory-based overloads of ReadAsync/WriteAsync methods in stream-based classes
Microsoft docsDescription
The memory-based method overloads have a more efficient memory usage than the byte array-based ones.
The rule works on ReadAsync and WriteAsync invocations of any class that inherits from System.IO.Stream.
The rule only works when the method is preceded by the await keyword.
| Detected method | Suggested method | |-----------------|------------------| |System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32,System.Threading.CancellationToken)|System.IO.Stream.ReadAsync(System.Memory{System.Byte},System.Threading.CancellationToken)| |System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32)|System.IO.Stream.ReadAsync(System.Memory{System.Byte},System.Threading.CancellationToken) with CancellationToken set to default in C#, or Nothing in Visual Basic.| |System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32,System.Threading.CancellationToken)|System.IO.Stream.WriteAsync(System.ReadOnlyMemory{System.Byte},System.Threading.CancellationToken)| |System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32)|System.IO.Stream.WriteAsync(System.ReadOnlyMemory{System.Byte},System.Threading.CancellationToken) with CancellationToken set to default in C#, or Nothing in Visual Basic.| Make sure to pass the offset and count integer arguments to the created Memory or ReadOnlyMemory instances. Rule CA1835 is available in all .NET versions where the memory-based overloads are available:
- .NET Standard 2.1 and above.
- .NET Core 2.1 and above.
Cause
This rule locates awaited invocations of the byte-array-based method overloads for ReadAsync and WriteAsync, and suggests using the memory-based method overloads instead, because they are more efficient.
How to fix violations
You can either fix them manually, or you can opt to let Visual Studio do it for you, by hovering over the light bulb that shows up next to the method invocation, and selecting the suggested change. Example:
!Code fix for CA1835 - Prefer the memory-based overloads of ReadAsync/WriteAsync methods in stream-based classes
The rule can detect a variety of violations for the ReadAsync and WriteAsync methods. Here are examples of the cases that the rule can detect:
### Example 1
Invocations of ReadAsync, without and with a CancellationToken argument:
Fix:
### Example 2
Invocations of WriteAsync, without and with a CancellationToken argument:
Fix:
### Example 3
Invocations with ConfigureAwait:
Fix:
Example
#pragma warning disable CA1835
// The code that's violating the rule is on this line.
#pragma warning restore CA1835When to suppress
It's safe to suppress a violation of this rule if you're not concerned about improving performance when reading or writing buffers in stream-based classes.