Created
June 25, 2019 07:20
-
-
Save davidfowl/046e86d9c532e3769cd38a6e7076f0b6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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