【发布时间】:2017-05-21 08:05:33
【问题描述】:
我正在尝试创建一个函数,该函数尝试在特定时间异步连接到主机,然后检查是否已建立连接。
我的问题是我无法为此异步连接添加持续时间。
我的功能:
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;
}
}
【问题讨论】:
-
client.Close在那里是多余的,因为您已经使用了using和client.Dispose(),无论如何都会执行关闭连接。实际上client.Close()执行client.Dispose() -
谢谢 fabio :) 我会改变我的工作解决方案
标签: c# asynchronous connection task tcpclient