Skip to content

Instantly share code, notes, and snippets.

@mterwoord
Created November 13, 2018 12:59
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 mterwoord/1e98eee12b0c3faf68b11901544b80e8 to your computer and use it in GitHub Desktop.
Save mterwoord/1e98eee12b0c3faf68b11901544b80e8 to your computer and use it in GitHub Desktop.
Socket extension
public static class SocketExtensions
{
public static Task ConnectExAsync(this Socket socket, string host, int port, CancellationToken cancellationToken = default)
{
var xCompletion = new TaskCompletionSource<bool>();
socket.BeginConnect(host,
port,
r =>
{
try
{
socket.EndConnect(r);
xCompletion.TrySetResult(true);
}
catch (Exception E)
{
xCompletion.TrySetException(E);
}
},
null);
cancellationToken.Register(() =>
{
xCompletion.SetException(new TimeoutException());
socket.Close();
});
return xCompletion.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment