C# - 具有特定持续时间的TcpClient异步连接

时间:2017-01-06 14:25:02

标签: c# asynchronous connection task tcpclient

我正在尝试创建一个尝试在特定时间内异步连接到主机的函数,然后检查是否已建立连接。

我的问题是我无法为此异步连接添加持续时间。

我的功能:

 public async Task<bool> IsConnected()
 {
        // Host IP Address and communication port
        string ipAddress = "192.168.0.11";
        int port = 9100;

        //Try to Connect with the host during 2 second
        {
            // Create TcpClient and try to connect
            using (TcpClient client = new TcpClient())
            { 
                Task<bool> mytask = client.ConnectAsync(ipAddress, port).Wait(TimeSpan.FromSeconds(2));
                bool isconnected = await mytask;

                if (isconnected)
                {
                    //Connection with host
                    return true;
                }
                else
                {
                    // No connection with host
                    return false;
                }
                //Close Connection
                client.Close();
            }
        }
        catch (Exception exception)
        {
            // Problem with connection
            return false;
        }
}

我有这个错误:

Cannot implicitly convert type 'bool' to 'System.Threading.Tasks.Task<bool>' at line :

Task<bool> mytask = client.ConnectAsync(ipAddress, port).Wait(TimeSpan.FromSeconds(2));

我到处搜索过,并没有找到解决方案。

感谢您的帮助

丹尼尔

工作解决方案:

 public async Task<bool> IsConnected()
 {
        // Host IP Address and communication port
        string ipAddress = "192.168.0.11";
        int port = 9100;

        //Try to Connect with the host during 2 second
        {
            // Create TcpClient and try to connect
            using (TcpClient client = new TcpClient())
            { 
                //Create Tasks
                var clientTask = client.ConnectAsync(ipAddress, port);
                var delayTask = Task.Delay(2000);

                //Check which one finish first
                var completedTask = await Task.WhenAny(new[] {clientTask, delayTask});

                //Check if the connection have been established before the end of the timer 
                return completedTask == clientTask;
            }
        }
        catch (Exception exception)
        {
            // Problem with connection
            return false;
        }
}

1 个答案:

答案 0 :(得分:6)

添加另一个延迟任务,然后使用返回第一个完成任务的Task.WhenAny 通过将完成的任务与客户端任务进行比较,您将决定&#34;哪个任务先完成

public async Task<bool> IsConnected()
{
    using (TcpClient client = new TcpClient())
    { 
        var clientTask = client.ConnectAsync(ipAddress, port);
        var delayTask = Task.Delay(2000);

        var completedTask = await Task.WhenAny(new[] {clientTask, delayTask});
        return completedTask == clientTask;
    }
}

请注意ConnectAsync方法返回Task而不是Task<bool>

异步方法返回类型Task的值。任务包含有关异步方法状态的信息(完成,运行,故障等)

等待&#34;等待&#34;你将等待并观察任务的结果(出现异常故障或出现故障)

所以基本上

// start connecting to host
var clientTask = client.ConnectAsync(ipAddress, port);

// start calculating elapsed time
var delayTask = Task.Delay(2000);

如果第一个任务出现异常,await Task.WhenAny将返回第一个完成任务或抛出异常的任务。