Open
Description
Type of issue
Typo
Description
Rule #3: If your method accepts Memory and returns void, you must not use the Memory instance after your method returns.
// !!! INCORRECT IMPLEMENTATION !!!
static void Log(ReadOnlyMemory<char> message)
{
// Run in background so that we don't block the main thread while performing IO.
Task.Run(() =>
{
StreamWriter sw = File.AppendText(@".\input-numbers.dat");
sw.WriteLine(message);
});
}
Consult similar implimentation
static int Log(ReadOnlyMemory<char> message)
{
var length = message.Length;
if (length == 0)
{
return 0;
}
Task.Run(() =>
{
StreamWriter sw = File.AppendText(@".\input-numbers.dat");
sw.WriteLine(message);
});
return length;
}
This method is int
returning and it violates same rule. It acceses Memory
parameter after it returned.
#3 is not related to return type but to fact that method is synchronous. Problem is that synchronous method sets up execution that accesses buffer after it returns.
Page URL
https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/memory-t-usage-guidelines
Content source URL
https://github.com/dotnet/docs/blob/main/docs/standard/memory-and-spans/memory-t-usage-guidelines.md
Document Version Independent Id
d6cf8d26-fb2f-7138-f0c7-ab529a5b9cde
Article author
Metadata
- ID: 4819512e-1044-1c57-0de1-447164220fd5
- Service: dotnet-fundamentals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment