Span<T> and async methods

Viewed 750

I've read a few of the articles on Span<T> (and ReadOnlySpan<T>) and how they musn't be used in async methods.

There was a great Chanel 9 video by Jared Parsons where he showed the following example:

static async Task<bool> IsCSharpIdentifierAsync(Memory<char> memory, StreamReader reader)
{
    var count = await reader.ReadAsync(memory);
    return IsCSharpIdentifier(memory.Span.Slice(0, count));
}

static bool IsCSharpIdentifier(ReadOnlySpan<char> value)
{
   ....
}

So, the overall flow might be asynchronous, but we're okay if we call out to a synchronous method that uses the Span.

Now, I've little if any knowledge about compilation, but I understand that the compiler might (in certain instances) "in-line" methods (i.e. copy the code from the called method into the calling method) to reduce the overhead of the method call.

I'm guessing the answer is "snort...of course not", but is there any chance that the compiler might inline a method using a Span into an async method? If so, that would lead to problems as I understand it.... (This includes "local methods")

1 Answers

The C# compiler never in-lines methods; the JIT might do that, but that is a separate level.

But: whether it does this or not is not actually all that relevant in this case. The thing that stops you using ref locals / ref structs in an async method is the fact that locals may need to be rewritten as fields. But JIT inlining is never going to create fields - it is only going to apply for local stack-based values, and local stack-based values are fine for ref values - since you clearly aren't going to have an await in the middle of your synchronous IsCSharpIdentifier code.

So: don't panic - the compiler and JIT will see you fine here.

Related