C# - 如果不存在设备,则在串口上检测设备挂起

C# - Detecting device on serial port hangs if no device exists

所以,我正在构建一个应用程序,它必须在继续之前检测设备是否连接到随机串行端口。虽然设备通过 USB 连接,但它被列为 COMPORT(在我的例子中是 COM5,但这取决于 PC)。如果插入设备,我有以下代码可以正常工作,没问题,只需一秒钟即可正常运行,但如果未连接与我要查找的名称匹配的设备,应用程序什么都不做,当它应该显示向上 messagebox 说没有连接任何设备。帮助将不胜感激。

ManagementScope connectionScope = new ManagementScope();
SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);
try
{
  foreach (ManagementObject item in searcher.Get())
  {
    string desc = item["Description"].ToString();
    string deviceId = item["DeviceID"].ToString();
    if (desc.Contains("Arduino"))
    {
      device_loc = deviceId;
      serializer.RunWorkerAsync();
      BeginInvoke((MethodInvoker)delegate
      {
         next_step.Enabled = true;
      });
    }
    else
    {
      MessageBox.Show("Could not detect any Arduino device connected, please connect your device.",
        "No device", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
      BeginInvoke((MethodInvoker)delegate
      {
          next_step.Text = "Ok, let's continue.";
          next_step.Enabled = true;
      });
    }
  }
}
catch (ManagementException xe)
{
  MessageBox.Show("Could not check for serial devices due to the following error: " + xe, 
    "Ooops", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

以上代码在单独的 backgroundworker 组件中运行。 正如我所说,如果设备已连接,它确实可以工作,如果设备未连接,我永远不会到达 messagebox 说它没有显示的地步。

您应该在显示 "Not detected any Arduino device" 之前完成 foreach 循环。您可以为此使用标志变量。请试试这个代码:

bool arduinoFound = false;
foreach (ManagementObject item in searcher.Get())
{
    string desc = item["Description"].ToString();
    if (desc.Contains("Arduino"))
    {
        arduinoFound = true;
    }
}

if (!arduinoFound)
    MessageBox.Show("Could not detect any Arduino device connected");