我试图同时检查多台服务器上的状态,但当我加载表单时,应用程序只是冻结,没有任何错误。这是我用来检查服务器状态的东西。知道吗?
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect("ip address here", port);
Status1.Text = "Online";
Status1.ForeColor = Color.Green;
}
catch (Exception)
{
Status1.Text = "Offline";
Status1.ForeColor = Color.Red;
}
try
{
tcpClient.Connect("ip address here", port);
Status2.Text = "Online";
Status2.ForeColor = Color.Green;
}
catch (Exception)
{
Status2.Text = "Offline";
Status2.ForeColor = Color.Red;
}
看看这个代码片段,它不会阻塞UI线程并保持表单响应。
static async Task CheckConnection()
{
TcpClient tcpClient = new TcpClient();
try
{
await tcpClient.ConnectAsync("ip address here", port);
Status1.Text = "Online";
Status1.ForeColor = Color.Green;
}
catch(AggregateException a)
{
Status1.Text = "Offline";
Status1.ForeColor = Color.Red;
}
catch (Exception)
{
Status1.Text = "Offline";
Status1.ForeColor = Color.Red;
}
}
如果你是这个编程模型的新手,请查看这个链接