TcpClient ConnectAsync获取状态

时间:2013-08-28 11:27:56

标签: c# sockets task-parallel-library

有什么办法可以获得TcpClient异步连接的状态吗?使用以下代码,如何使用Connected属性获取客户端的状态?我尝试异步建立远程连接,但同时不要等待超过5秒......

TcpClient client = new TcpClient();

Task tsk = Task.Factory.StartNew(() =>
{
   client.ConnectAsync(host, port);

   // client.Connect   (this is always false)
});

tsk.Wait(5000);

// client.Connect   (or if I use it here, this is always false)

2 个答案:

答案 0 :(得分:11)

不,@Jon错了! IsCompleted只会告诉您任务是否已完成,并且表示已建立连接。例如,如果特定地址/端口上没有打开服务器,IsCompleted将返回true ...您应该检查IsFaulted

以下是我从互联网上整理过的代码,实际上我已经测试了

string address = "127.0.0.1";
int port = 8888;
int connectTimeoutMilliseconds = 1000;

var tcpClient = new TcpClient();
var connectionTask = tcpClient
    .ConnectAsync(address, port).ContinueWith(task => {
        return task.IsFaulted ? null : tcpClient;
    }, TaskContinuationOptions.ExecuteSynchronously);
var timeoutTask = Task.Delay(connectTimeoutMilliseconds)
    .ContinueWith<TcpClient>(task => null, TaskContinuationOptions.ExecuteSynchronously);
var resultTask = Task.WhenAny(connectionTask, timeoutTask).Unwrap();

resultTask.Wait();
var resultTcpClient = resultTask.Result;
// Or shorter by using `await`:
// var resultTcpClient = await resultTask;

if (resultTcpClient != null)
{
    // Connected!
}
else
{
    // Not connected
}

答案 1 :(得分:8)

首先,不要创建自己的新Task;这是一个错误。 ConnectAsync已经返回表示连接尝试的Task

var tsk = client.ConnectAsync(host, port);
tsk.Wait(5000);

等待返回后,检查任务的IsCompleted属性;当且仅当连接已建立时,它将为true