Consider the following program:
using System;
using System.Diagnostics;
using System.Net.Sockets;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Socket sock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
try
{
Stopwatch watch = new Stopwatch();
watch.Start();
IAsyncResult res = sock.BeginConnect("localhost", 7000, null, null);
res.AsyncWaitHandle.WaitOne( 5000 ); // 5 sec timeout
watch.Stop();
Console.WriteLine("Elapsed ms: " + watch.ElapsedMilliseconds);
if (!sock.Connected) {
sock.Close();
Console.WriteLine("Failed to connect server.");
}
}
catch (System.Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}
Console Output:
Elapsed ms: 1014
Failed to connect server.
I would have expected for BeginConnect
to try to establish the connection for about 5 seconds, whereas the wait always returns after just 1 second.
Why?