How to use `Memory<T>` after `Task` final state transition?
- 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 #4: If your method accepts a Memory and returns a Task, you must not use the Memory instance after the Task transitions to a terminal state.
```csharp
// An acceptable implementation.
static Task Log(ReadOnlyMemory message)
{
// Run in the background so that we don't block the main thread while performing IO.
return Task.Run(() =>
{
StreamWriter sw = File.AppendText(@".\input-numbers.dat");
sw.WriteLine(message);
sw.Flush();
});
}
```
### Problem
First, paper does not show this kind of violation. Code sample is same as that in rule #3 where it is provided as solution to problem given.
Second, FMPOV it is needle in hay task to find such case, when method is `Task`-returning, final state is observed by its consumer/caller. How it is possible for it to continue working on its parameter when it already returned?
```csharp
static Task Log(ReadOnlyMemory message)
{
var taks = Task.Run(() =>
{
StreamWriter sw = File.AppendText(@".\input-numbers.dat");
sw.WriteLine(message);
sw.Flush();
});
Task.Wait();
// work after terminal state but method did not returned
var x = message.ToString();
}
```
```csharp
static async Task Log(ReadOnlyMemory message)
{
await Task.Run(() =>
{
StreamWriter sw = File.AppendText(@".\input-numbers.dat");
sw.WriteLine(message);
sw.Flush();
});
// method likely yielded control on `await` before but `Task` generated by _async state machine_ is not in terminal state
var x = message.ToString();
}
```
I can list more examples but none of them would show hot to work with its _parameter_ after _return_.
### 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.