Created
November 13, 2018 12:59
-
-
Save mterwoord/1e98eee12b0c3faf68b11901544b80e8 to your computer and use it in GitHub Desktop.
Socket extension
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 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