检查服务器状态

时间:2020-05-06 10:30:15

标签: c#

我试图同时检查多个服务器上的状态,但是当我加载表单时,应用程序只是冻结而没有任何错误。这就是即时通讯用来检查服务器状态的内容。有想法吗?

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;
}

1 个答案:

答案 0 :(得分:0)

看看此代码段,这不会阻塞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;
        }

    }

如果您是此编程模型的新手,请查看此link