docs icon indicating copy to clipboard operation
docs copied to clipboard

Why is `Memory<T>` parameter access restricted only in `void`-returning method?

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 #3: If your method accepts Memory<T> and returns void, you must not use the Memory<T> 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

@gewarren

Metadata

  • ID: 4819512e-1044-1c57-0de1-447164220fd5
  • Service: dotnet-fundamentals

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