Writing to MemoryStream with foreach As you can see here:



20% CPU in a 3 minutes and 20 seconds excessive 40 executions async/await at a time for 9700 times caused quite a bit of CPU usage.

Code:

public MemoryStream getMessageBody()
{
    #region Get MessageBody
    IEnumerable&lt;BytesWraper&gt; MessageBody = GetMessageBodySource();
    if (MessageBody == null) {
        return null;
    }
    #endregion
    #region Write MessageBody's Data to a MemoryStream so we can convert it later to a String
    MemoryStream memoryStream = new MemoryStream(ContentLength == -1 ? 0 : ContentLength);
    try {
        foreach (BytesWraper bytes in MessageBody) {
            memoryStream.Write(bytes.Value, 0, bytes.Length);
        }
    } catch (Exception) {
        return null;
    }
    #endregion
    if (ConnectionClosed()) {
        _request.Dispose();
    }
    MessageBodyLoaded = true;
    return memoryStream;
}


Is there a way here to reduce the amount of usage by this foreach call? Perhaps not need to do it at all?

All im then doing with the result is as follows:

return MessageBody != null ? CharacterSet.GetString(MessageBody.GetBuffer(), 0, (int)MessageBody.Length) : null


(where MessageBody is getMessageBody())
Have you tried something like this (?):

MemoryStream memoryStream = new MemoryStream(MessageBody.SelectMany(mb =&gt; mb.Value).ToArray());