Use CancellableTask to implement TCP Connection Request timeout

Source: Internet
Author: User
Tags apm
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.