Skip to content

Instantly share code, notes, and snippets.

@halter73
Forked from davidfowl/pipes.cs
Created July 13, 2017 07:57
Show Gist options
  • Save halter73/28a43bd84a6ce1ca8f93a3144ef079c1 to your computer and use it in GitHub Desktop.
Save halter73/28a43bd84a6ce1ca8f93a3144ef079c1 to your computer and use it in GitHub Desktop.
Pipe sample
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines;
namespace WebApplication19
{
public class Program
{
public static async Task Main(string[] args)
{
PipeFactory factory = new PipeFactory();
IPipe pipe = factory.Create();
Task writes = DoWrites(pipe.Writer);
Task reads = DoReads(pipe.Reader);
await Task.WhenAll(writes, reads);
}
private static async Task DoReads(IPipeReader reader)
{
while (true)
{
ReadResult result = await reader.ReadAsync();
ReadableBuffer buffer = result.Buffer;
ReadCursor consumed = buffer.Start;
ReadCursor examined = buffer.End;
try
{
if (!buffer.IsEmpty)
{
if (TryParseNewLine(buffer, out consumed, out examined, out ReadableBuffer line))
{
// Print the line if we have one
Console.WriteLine(line);
}
else if (result.IsCompleted)
{
Console.WriteLine("Writing ended before sending a '\\r' discarding message");
break;
}
}
else if (result.IsCompleted)
{
Console.WriteLine("Writer completed");
break;
}
}
finally
{
reader.Advance(consumed, examined);
}
}
reader.Complete();
}
private static bool TryParseNewLine(ReadableBuffer buffer, out ReadCursor consumed, out ReadCursor examined, out ReadableBuffer line)
{
// Look for a '\r'
if (ReadCursorOperations.Seek(buffer.Start, buffer.End, out ReadCursor found, (byte)'\r') != -1)
{
line = buffer.Slice(buffer.Start, found);
// This is basically found++ skipping over \r
found = buffer.Move(found, 1);
// Mark consumed and examined
consumed = found;
examined = found;
return true;
}
else
{
consumed = buffer.Start;
examined = buffer.End;
line = default;
return false;
}
}
private static async Task DoWrites(IPipeWriter writer)
{
try
{
while (true)
{
// Console.ReadLine and Console.In.ReadLineAsync is blocking
ConsoleKeyInfo keyInfo = await Task.Run(() => Console.ReadKey());
if (keyInfo.Key == ConsoleKey.Escape)
{
break;
}
if (keyInfo.Key == ConsoleKey.Enter)
{
Console.WriteLine();
}
WritableBuffer wb = writer.Alloc();
wb.Write(Encoding.UTF8.GetBytes(new[] { keyInfo.KeyChar }));
await wb.FlushAsync();
}
}
finally
{
writer.Complete();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment