cogumel0
cogumel0

Reputation: 2661

HttpContent.ReadAsByteArrayAsync() clarification

It is not clear enough from the documentation whether HttpContent.ReadAsByteArrayAsync() takes the content already existing in memory and copies the content to a new byte[] which it then returns to the consumer, or whether the byte[] it returns is effectively pointing to the same location that the already existing content in memory is at.

In other words, can someone clarify whether there's new memory allocated for the returned byte[] or not?

I'm specifically asking about .NET 5 by the way.

Upvotes: 1

Views: 842

Answers (1)

Enigmativity
Enigmativity

Reputation: 117064

If you decompile the ReadAsByteArrayAsync method you get this:

private MemoryStream bufferedContent;

[global::__DynamicallyInvokable]
public Task<byte[]> ReadAsByteArrayAsync()
{
    CheckDisposed();
    TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>();
    LoadIntoBufferAsync().ContinueWithStandard(delegate(Task task)
    {
        if (!HttpUtilities.HandleFaultsAndCancelation(task, tcs))
        {
            tcs.TrySetResult(bufferedContent.ToArray());
        }
    });
    return tcs.Task;
}

[__DynamicallyInvokable]
public virtual byte[] ToArray()
{
    byte[] array = new byte[_length - _origin];
    Buffer.InternalBlockCopy(_buffer, _origin, array, 0, _length - _origin);
    return array;
}

The .ToArray() call clearly allocates new memory.

Upvotes: 2

Related Questions