Why is `Memory<T>` parameter access restricted only in `void`-returning method?
- Dominant language
- No language data
- Stars
- 4.8k
- Forks
- 6.1k
- Avg merge
- 19h 10m
- Merged PRs (30d)
- 268
Description
### Type of issue
Typo
### Description
From https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/memory-t-usage-guidelines#usage-guidelines
> Rule #3: If your method accepts Memory and returns void, you must not use the Memory instance after your method returns.
```csharp
// !!! INCORRECT IMPLEMENTATION !!!
static void Log(ReadOnlyMemory 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
```csharp
static int Log(ReadOnlyMemory 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
@gewarren
### Metadata
* ID: 4819512e-1044-1c57-0de1-447164220fd5
* Service: **dotnet-fundamentals**
Contributor guide
Assessment
This issue has not been assessed yet.