MemoryStream.ToArray() gets stuck for 10 seconds

ahmet sahgoz 0 Reputation points
2025-01-28T17:22:00.01+00:00

I have been using MemoryStream.ToArray() for 8 years in a very hot path in our application. After .net8 upgrade from .netfreamework.V4.6.1 I realized my application gets stuck if I call MemoryStream.ToArray() function for 2 GB's of data, it does not matter if i call it 2000 times for 1 MB or 40 times for 50MB. I realized the reason behind this is that you changed the function from C++ based one to new GC.AllocateUninittializedArray<byte> one. My hot path thread waits until GC allocates a new unitialized array and I assume it takes time to collect garbage if i filled the memory for 2 GB beforehand.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,087 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 48,861 Reputation points Microsoft Vendor
    2025-01-29T02:54:26.2366667+00:00

    Hi @ahmet sahgoz , Welcome to Microsoft Q&A,

    Try Use TryGetBuffer().

    If the MemoryStream is not resizable (MemoryStream.CanWrite == false), TryGetBuffer() provides a view without copying (if you control the MemoryStream and it does not expose unnecessary data, you can use MemoryStream.GetBuffer()):

    if (memoryStream.TryGetBuffer(out ArraySegment<byte> segment))
    {
        byte[] buffer = segment.Array;
        int offset = segment.Offset;
        int length = segment.Count;
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.