Microsoft Technologies based on the .NET software framework. Miscellaneous topics that do not fit into specific categories.
Hi @Henric Jungheim , Welcome to Microsoft Q&A,
Given the constraints and the need to efficiently manage buffer sizes without relying heavily on internal details, you can focus on using Advance and FlushAsync more strategically, along with leveraging PipeWriter.CreateBuffer to handle the memory management more efficiently.
var remaining = int.MaxValue;
const int flushThreshold = 131070; // Adjust based on your needs
await foreach (var thing in source.ReadEmAllAsync())
{
var size = thing.Size;
// If the remaining space in the buffer is not enough for the new data
if (size > remaining)
{
await writer.FlushAsync();
remaining = int.MaxValue; // Reset remaining after flush
}
var buffer = writer.GetMemory(size);
thing.CopyTo(buffer.Span[..size]);
remaining = buffer.Length - size;
writer.Advance(size);
// Optionally, flush based on a threshold to avoid over-accumulating
if (writer.UnflushedBytes >= flushThreshold)
{
await writer.FlushAsync();
remaining = int.MaxValue; // Reset remaining after flush
}
}
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.