1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00

Optimized response stream buffer

This commit is contained in:
Uncled1023 2022-05-21 09:29:24 -07:00
parent 169ec3d919
commit e5a4f3b171

View File

@ -16,44 +16,34 @@ namespace Teknik.Utilities
try try
{ {
int processedBytes = 0; int processedBytes = 0;
byte[] buffer = new byte[chunkSize]; var bufferSize = chunkSize;
int bytesRemaining = length; if (length < chunkSize)
int bytesToRead = chunkSize; bufferSize = length;
Memory<byte> buffer = new byte[bufferSize];
do do
{ {
if (chunkSize > bytesRemaining) processedBytes = await stream.ReadAsync(buffer);
{
bytesToRead = bytesRemaining;
}
processedBytes = stream.Read(buffer, 0, bytesToRead);
if (processedBytes > 0) if (processedBytes > 0)
{ {
await response.Body.WriteAsync(buffer, 0, processedBytes); await response.Body.WriteAsync(buffer.Slice(0, processedBytes));
// Flush the response // Flush the response
if (flush) if (flush)
{ {
await response.Body.FlushAsync(); await response.Body.FlushAsync();
} }
// Clear the buffer
Array.Clear(buffer, 0, chunkSize);
// decrement the total bytes remaining to process
bytesRemaining -= processedBytes;
} }
} }
while (processedBytes > 0 && bytesRemaining > 0); while (processedBytes > 0);
} }
catch (Exception) catch (Exception)
{ {
// Don't worry about it. Just leave // Don't worry about it. Just leave
await response.Body.FlushAsync();
} }
finally finally
{ {
await response.Body.FlushAsync(); await response.Body.FlushAsync();
// dispose of file stream // dispose of file stream
stream?.Dispose(); stream?.Dispose();
} }