Skip to content

Instantly share code, notes, and snippets.

@benaadams
Forked from davidfowl/NagleAwaitable.cs
Created April 12, 2018 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benaadams/adf677efcc419b4537d176049b278461 to your computer and use it in GitHub Desktop.
Save benaadams/adf677efcc419b4537d176049b278461 to your computer and use it in GitHub Desktop.
const int maxBuffer = 1024;
while (true)
{
var result = await application.Output.ReadAsync();
var buffer = result.Buffer;
// Check if we have enough to perform a write
if (buffer.Length >= maxBuffer)
{
await WriteAsync(buffer);
}
else
{
while (buffer.Length < maxBuffer)
{
var length = buffer.Length;
// If we're under, we want to start buffering, act like we consumed
// nothing but looked at everything so we can wait for more data
application.Output.AdvanceTo(buffer.Start, buffer.End);
// Dispatch to the thread pool to inject some latency (this *could* be another queue)
await Task.Yield();
// TryRead should *always* return true since we know we have something to write
var hasData = application.Output.TryRead(out result);
buffer = result.Buffer;
Debug.Assert(hasData, "We should have data buffered");
if (buffer.Length == length)
{
// We didn't get more data so write what we have
break;
}
}
await WriteAsync(buffer);
}
application.Output.AdvanceTo(buffer.End);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment