首页 > Windows开发 > 详细

C# 给TcpClient的Connect方法设置超时时间

时间:2018-12-26 16:20:00      阅读:592      评论:0      收藏:0      [点我收藏+]
var client = new TcpClient();
var result = client.BeginConnect("remotehost", this.Port, null, null);

var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

if (!success)
{
    throw new Exception("Failed to connect.");
}

// we have connected
client.EndConnect(result);

 

 

.Net 4.5的简便写法

 

var client = new TcpClient();
if (!client.ConnectAsync("remotehost", remotePort).Wait(1000))
{
    // connection failure
}

 

代码出处: https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient

C# 给TcpClient的Connect方法设置超时时间

原文:https://www.cnblogs.com/xyz0835/p/10179665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!