Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
多线程串行端口C#_C#_Multithreading_Serial Port - Fatal编程技术网

多线程串行端口C#

多线程串行端口C#,c#,multithreading,serial-port,C#,Multithreading,Serial Port,我目前正在编写一个执行3个基本功能的应用程序: 向第三方设备发送命令 读取第三方设备的字节响应 分析响应并将分析写入RichTextBox 我的应用程序包含许多测试脚本,每个脚本执行一个测试循环,例如: public SerialPort comport = new SerialPort(); private void RunTest() { byte[] arrayExample = { 0x00, 0x01, 0x02, 0x03 }; // Perform 200 op

我目前正在编写一个执行3个基本功能的应用程序:

  • 向第三方设备发送命令
  • 读取第三方设备的字节响应
  • 分析响应并将分析写入RichTextBox
  • 我的应用程序包含许多测试脚本,每个脚本执行一个测试循环,例如:

    public SerialPort comport = new SerialPort();
    
    private void RunTest()
    {
        byte[] arrayExample = { 0x00, 0x01, 0x02, 0x03 };
    
        // Perform 200 operations and analyze responses
        for(int i=0, i<200, i++)
        {
    
            // Send byte array to 3rd party device
            comport.Write(arrayExample, 0, arrayExample.length);
    
            // Receive response
            int bytes = comport.BytesToRead;            
            byte[] buffer = new byte[bytes];
            comport.Read(buffer, 0, bytes);
    
            // Check to see if the device sends back a certain byte array
            if(buffer = { 0x11, 0x22 })
            {
               // Write "test passed" to RichTextBox
               LogMessage(LogMsgType.Incoming, "Test Passed");
            }
            else
            {
               // Write "test failed" to RichTextBox
               LogMessage(LogMsgType.Incoming, "Test Failed");
            }
        }
    }
    
    public SerialPort comport=new SerialPort();
    私有void RunTest()
    {
    字节[]arrayExample={0x00,0x01,0x02,0x03};
    //执行200个操作并分析响应
    
    对于(inti=0,i您需要在另一个线程上运行它

    Thread testThread = new Thread(() => RunTest());
    testThread.Start();
    
    我想

    LogMessage();
    
    正在访问UI。线程不允许您直接访问UI,因此最简单的方法是匿名。在LogMessage中,您可以执行以下操作

    this.Invoke((MethodInvoker)delegate { richTextBox.Text = yourVar; });
    

    是的,在一个工作线程中运行整个RunTest函数。谢谢你,我会尝试一下让我听起来像个新手(我是)但是,我应该在哪里插入此代码。目前我正在键入一个按钮单击事件的测试脚本。我会将其放置在实际的测试脚本中吗?还是放置在按钮单击事件代码中?您会将其添加到您的单击事件中。您还希望向用户指出,在其运行时发生了一些事情。非常感谢。您已经是一名trem慷慨的帮助!