模拟TcpClient的Timeout

using (TcpClient tcp = new TcpClient())   
{   
    IAsyncResult ar = tcp.BeginConnect("127.0.0.1", 80, null, null);   
    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;   
    try  
    {   
       if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))   
       {   
           tcp.Close();   
           throw new TimeoutException();   
       }   
  
        tcp.EndConnect(ar);   
    }   
    finally  
    {   
        wh.Close();   
    }   
}  
posted on 2012-12-25 11:50  野文  阅读(680)  评论(0编辑  收藏  举报