Skip to content

Instantly share code, notes, and snippets.

@ProximaB
Created January 21, 2018 23:00
Show Gist options
  • Select an option

  • Save ProximaB/11f1e5ebeafd3166e237108104ded15b to your computer and use it in GitHub Desktop.

Select an option

Save ProximaB/11f1e5ebeafd3166e237108104ded15b to your computer and use it in GitHub Desktop.
Canselation Token
public void Stop()
{
this.Status = ServerStatus.Stopping;
this.listener.Stop();
this.cancellationTokenSource.Cancel();
this.Status = ServerStatus.Stopped;
}
private async void ListenForConnections(CancellationToken cancellationToken)
{
try
{
while (this.Status == ServerStatus.Running)
{
var socketTask = this.listener.AcceptSocketAsync();
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
{
if (socketTask != await Task.WhenAny(socketTask, tcs.Task).ConfigureAwait(false))
break;
}
var context = new TcpContext(socketTask.Result);
this.OnConnectionReceived(context);
}
}
catch (ObjectDisposedException)
{
// Closed
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment