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):

// 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();
}
' 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.