Introduction
System. Net. Sockets. TcpClient and System. Net. Sockets. Socket of. Net do not directly provide timeout control mechanism for Connect/BeginConnect. Therefore, when the server is not listening, or a network failure occurs, the client connection request will be forced to wait for a long time until an exception is thrown. The default wait time is 20 ~ 30 s .. SocketOptionName. SendTimeout of the Net Socket Library provides control over the timeout time for data sending, but it is not the timeout time for connection requests discussed in this article. [1]
The CancellableTask introduced in the previous article ". Net Cancellable Task-APM asynchronous timeout mechanism extension" provides the asynchronous timeout/Cancellation mechanism extension of the APM model. Now, you can download the source code and Sample of CancellableTask on Codeplex.
Implementation
The following describes how to use CancellableTask to implement TCP Connection Request timeout mechanism:
Public TcpClient Connect (string ip, int port, int timeout)
{
TcpClient client = new TcpClient ();
WorkCallback workCallback = delegate (object state)
{
Client. Connect (ip, port); return null;
};
CancelCallback cancelCallback = delegate (object cancelState)
{
Client. Close (); return null;
};
CancellableTask task = new CancellableTask (workCallback );
IAsyncResult ar = task. BeginInvoke (null, cancelCallback, null, timeout );
Task. EndInvoke (ar );
Return tcpClient;
}
Once the client. Connect times out, cancelCallback forcibly closes the TCP connection, causing the blocked client. Connect to throw an exception and return it. Note: Exceptions in workCallback will be thrown again at task. EndInvoke.
Related Links
1. [translation] C # Socket connection request timeout Mechanism
2.. Net Cancellable Task-APM asynchronous timeout mechanism Extension
3. CancellableTask on CodePlex