串口读取导致应用程序冻结一段时间-我需要线程吗?



我用c#写了一些代码来读取AT命令兼容调制解调器的结果。如果我开始COM端口读取整个应用程序冻结,直到数据收到。我想我应该使用线程,但我不知道怎么做?

        if (!serialPort1.IsOpen)
            serialPort1.Open();
        serialPort1.WriteTimeout = 5000;
        serialPort1.NewLine = "rn";
        serialPort1.WriteLine("AT#MON");
        serialPort1.NewLine = "rn";
        while (true) // Loop indefinitely
        {
            serialPort1.NewLine = "rn"; // Prompt
            string linee = serialPort1.ReadLine(); // Get string from port
            if (System.Text.RegularExpressions.Regex.IsMatch(linee, ("^xcqa:")))
            {
                textBox1.AppendText(System.Environment.NewLine);
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(linee, ("^fkss:")))
            {
                textBox1.AppendText(System.Environment.NewLine);
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(linee, ("ended"))) // Check string
            {
                break;
            }
            textBox1.AppendText(linee);
        }

是。您需要使用多线程。生成一个新线程将允许应用程序中的其他代码同时进行。为此,您的串行端口读取代码将需要自己的线程。阅读c#的多线程文档。

    <
  • 线程教程/gh>c#中的线程
  • c#多线程入门

最新更新