Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Created June 25, 2019 07:20
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 davidfowl/046e86d9c532e3769cd38a6e7076f0b6 to your computer and use it in GitHub Desktop.
Save davidfowl/046e86d9c532e3769cd38a6e7076f0b6 to your computer and use it in GitHub Desktop.
public class NamedPipeConnectionListener : IConnectionListener
{
private readonly NamedPipeEndPoint _endpoint;
private readonly CancellationTokenSource _listeningSource = new CancellationTokenSource();
public NamedPipeConnectionListener(NamedPipeEndPoint endpoint)
{
_endpoint = endpoint;
ListeningToken = _listeningSource.Token;
}
public EndPoint EndPoint => _endpoint;
public CancellationToken ListeningToken { get; }
public async ValueTask<ConnectionContext> AcceptAsync(CancellationToken cancellationToken = default)
{
if (ListeningToken.IsCancellationRequested)
{
// We're done listening
return null;
}
var stream = new NamedPipeServerStream(_endpoint.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, _endpoint.PipeOptions);
CancellationTokenSource source = null;
CancellationToken effectiveToken = default;
if (cancellationToken.CanBeCanceled)
{
source = CancellationTokenSource.CreateLinkedTokenSource(effectiveToken, ListeningToken);
effectiveToken = source.Token;
}
else
{
effectiveToken = ListeningToken;
}
try
{
using (source)
{
await stream.WaitForConnectionAsync(effectiveToken);
}
}
catch (OperationCanceledException) when (ListeningToken.IsCancellationRequested)
{
// Cancelled the current token
return null;
}
catch (ObjectDisposedException)
{
// Listener disposed
return null;
}
return new NamedPipeConnectionContext(stream);
}
public ValueTask DisposeAsync()
{
_listeningSource.Dispose();
return default;
}
public ValueTask UnbindAsync(CancellationToken cancellationToken = default)
{
_listeningSource.Cancel();
return default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment