docs icon indicating copy to clipboard operation
docs copied to clipboard

How to use `Memory<T>` after `Task` final state transition?

Open deep-outcome opened this issue 1 year ago • 0 comments

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<T> and returns a Task, you must not use the Memory<T> instance after the Task transitions to a terminal state.

// An acceptable implementation.
static Task Log(ReadOnlyMemory<char> 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?

static Task Log(ReadOnlyMemory<char> 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();
}
static async Task Log(ReadOnlyMemory<char> 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

deep-outcome avatar Oct 09 '24 12:10 deep-outcome