Objective benefit of static local function that’s only called once?

Recently I was looking at the source code of Stream.CopyToAsync, which is available here on github.

The author first validates the parameters and then calls a static local function that does the actual processing. I find static local functions to be quite useful when I need to reuse a functionality, but don’t wan’t to add yet another private method.

But in Stream.CopyToAsync the static local function is called just once at the very end of the declaring method. I don’t see any benefit here.

=> Is there any objective benefit (i.e. performance, security, better compiler optimizations, memory usage, …) to use a static local function here?

Please note that I’m not asking about readability, because that’s somewhat opinionated.

Code:

public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
    ValidateCopyToArguments(destination, bufferSize);
    if (!CanRead)
    {
        if (CanWrite)
        {
            ThrowHelper.ThrowNotSupportedException_UnreadableStream();
        }

        ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name);
    }

    return Core(this, destination, bufferSize, cancellationToken);

    static async Task Core(Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken)
    {
        byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
        try
        {
            int bytesRead;
            while ((bytesRead = await source.ReadAsync(new Memory<byte>(buffer), cancellationToken).ConfigureAwait(false)) != 0)
            {
                await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false);
            }
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(buffer);
        }
    }
}

Which is in my opinion exactly the same as without a static local function:

public virtual async Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
    ValidateCopyToArguments(destination, bufferSize);
    if (!CanRead)
    {
        if (CanWrite)
        {
            ThrowHelper.ThrowNotSupportedException_UnreadableStream();
        }

        ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name);
    }

    // return Core(this, destination, bufferSize, cancellationToken);

    byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
    try
    {
        int bytesRead;
        while ((bytesRead = await this.ReadAsync(new Memory<byte>(buffer), cancellationToken).ConfigureAwait(false)) != 0)
        {
            await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false);
        }
    }
    finally
    {
        ArrayPool<byte>.Shared.Return(buffer);
    }
}

3

Sweeper gave a good explanation in the comments, which I will summarize here.
Also this question and this microsoft devblog post and especially this blog post helped me understand the great idea behind this.
Key points:

  • The static local function Core encapsulates all async operations of Stream.CopyToAsync -> the compiler will transform Core to an async state machine.
  • Stream.CopyToAsync itself is not async and will not be transformed to a state machine.
  • If an exception is thrown during validation (befor the call to Core) the exception will directly be passed on to the caller.
  • Exceptions thrown in Core will only be passed to the caller when the resulting Task is awaited.

Minmalistic example, as of my understanding:

Task Foo(Argument arg)
{
    if(!arg.IsValid) throw new ArgumentException();

    return Core(arg);

    static async Task Core(Argument arg) { await SomeAsyncOperations(); }
}

async Task Bar(Argument arg)
{
    if(!arg.IsValid) throw new ArgumentException();

    await SomeAsyncOperations();   
}

// no difference in usage when awaited immediately

await Foo(invalidArg); // throws here
await Bar(invalidArg); // throws here

// big difference if awaited somewhere else (or not awaited at all)

var fooTask = Foo(invalidArg); // throws here (!)
await fooTask;

var barTask = Bar(invalidArg); // no throw here (!)
await barTask; // throws here

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật