WinForms - 睡眠后未设置或设置文本

时间:2017-09-06 14:52:17

标签: c# winforms arduino

我刚刚开始学习如何开发Windows窗体应用程序。我已经用C#编程了几年(在Unity3D中)。

我目前正在开发一个连接到Arduino的HMI(人机界面)应用程序。我已经有了它的工作;即:我可以连接到它并读取/写入Arduino。因此,以下代码为WORKS(就通信而言)。

private void ConnectToArduino () {
    labelMonitorConnectionStatus.Text = "Connecting...";

    string selectedPort = comboBoxMonitorComPorts.GetItemText (comboBoxMonitorComPorts.SelectedItem);
    port = new SerialPort (selectedPort, 9600, Parity.None, 8, StopBits.One);

    try {
        port.Open ();

        while (port.BytesToRead > 0)
            port.ReadByte ();

        port.Write ("CPU0CN\n");

        Thread.Sleep (3000);

        if (port.BytesToRead > 0) {
            String response = port.ReadLine ();

            if (response.Equals ("test")) {
                labelMonitorConnectionStatus.Text = "Connected";
                btnMonitorConnect.Text = "Disconnect";
                isConnected = true;

                EnableControls ();
            }
            else {
                labelMonitorConnectionStatus.Text = "Connection Failed!";
                btnMonitorConnect.Text = "Connect";
                isConnected = false;

                port.Close ();
                ResetControls ();
            }
        }
        else {
            labelMonitorConnectionStatus.Text = "Connection Failed!";
            btnMonitorConnect.Text = "Connect";
            isConnected = false;

            port.Close ();
            ResetControls ();
        }
    }
    catch (Exception e) {
        labelMonitorConnectionStatus.Text = "Connection Failed!";
        btnMonitorConnect.Text = "Disconnect";

        ResetControls ();
    }
}

该代码通过串行com端口将我成功连接到Arduino。让我们关注代码的这一部分:

labelMonitorConnectionStatus.Text = "Connecting...";

string selectedPort = comboBoxMonitorComPorts.GetItemText (comboBoxMonitorComPorts.SelectedItem);
port = new SerialPort (selectedPort, 9600, Parity.None, 8, StopBits.One);

try {
    port.Open ();

    while (port.BytesToRead > 0)
        port.ReadByte ();

    port.Write ("CPU0CN");

    Thread.Sleep (3000);

labelMonitorConnectionStatus.Text = "Connecting..."; labelMonitorConnectionStatus 上的文本设置为“正在连接...”

port.Open (); 打开端口......

port.Write ("CPU0CN\n"); 通过COM端口写入通信启动请求消息

Thread.Sleep (3000); 等待3秒钟从com端口响应(当然会稍后减少)

这应该将文本更改为“正在连接...”,然后等待3秒再更改为“连接失败!”或“已连接”。但是,这种情况并没有发生。发生了什么事情是线程将睡眠3秒 - 没有将文本设置为“正在连接...” - 然后立即更改为“连接失败!”或“已连接”。换句话说,我从未在应用程序上看到“正在连接...”。我看到“未连接”3秒钟,然后“连接失败!”或“已连接”。

Watch this short clip to understand what I see

先谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

windows会在看到更改时按顺序处理所有事件,而不是在您调用的每个语句之后。所以你的睡眠命令会干扰更新标签

尝试在设置文本后立即在标签上调用更新命令。

labelMonitorConnectionStatus.Text = "Connecting...";
labelMonitorConnectionStatus.Update();

如果这没有帮助,请像这样更新整个表单

labelMonitorConnectionStatus.Text = "Connecting...";
Update();