Skip to content

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

Open

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.

// !!! 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions