Skip to content

Files

Latest commit

 

History

History
43 lines (32 loc) · 1.1 KB

File metadata and controls

43 lines (32 loc) · 1.1 KB

Pattern: Missing use of memory-based overload of ReadAsync/WriteAsync

Issue: -

Description

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 Stream.

The rule only works when the method is preceded by the await keyword.

Example of incorrect code:

public async void TestMethod(CancellationToken ct)
{
	using (FileStream s = new FileStream("path.txt", FileMode.Create))
	{
		byte[] buffer = new byte[s.Length];
		await s.ReadAsync(buffer, 0, buffer.Length);
		await s.ReadAsync(buffer, 0, buffer.Length, ct);
	}
}

Example of correct code:

public async void TestMethod(CancellationToken ct)
{
	using (FileStream s = new FileStream("path.txt", FileMode.Create))
	{
		byte[] buffer = new byte[s.Length];
		await s.ReadAsync(buffer.AsMemory(0, buffer.Length));
		await s.ReadAsync(buffer.AsMemory(0, buffer.Length), ct);
	}
}

Further Reading