How to shorten Connect timeout

Connect and BeginConnect methods take quite a long time to timeout, when you use incorrect server address. It usually takes almost 20 seconds for those methods to decide that connection is impossible. Setting SendTimeout/ReceiveTimeout doesn’t influence this in any way.

Not only Imap, Pop3, and Smtp classes suffer from this problem, it’s the same for regular Socket class.

There is a solution however, using BeginConnect and simply waiting for specified amount of time (AsyncWaitHandle.WaitOne) without calling EndConnect (which blocks):

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
// C#
 
using(Imap imap =new Imap())
{
    IAsyncResult result = imap.BeginConnectSSL("imap.example.com");
 
    // 5 seconds timeout
    bool success = result.AsyncWaitHandle.WaitOne(5000, true);
 
    if (success == false)
    {
        throw new Exception("Failed to connect server.");
    }
    imap.EndConnect(result);
 
    //...
 
    imap.Close();
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
' VB.NET
 
Using imap As New Imap()
    Dim result As IAsyncResult = imap.BeginConnectSSL("imap.example.com")
 
    ' 5 seconds timeout
    Dim success As Boolean = result.AsyncWaitHandle.WaitOne(5000, True)
 
    If success = False Then
        Throw New Exception("Failed to connect server.")
    End If
    imap.EndConnect(result)
 
    '...
 
    imap.Close()
End Using

Tags:   

Questions?

Consider using our Q&A forum for asking questions.