2014-02-26 44 views
0

我目前正在写,执行3种基本功能的应用程序:多线程的串行端口C#

  1. 发送命令到第三方设备
  2. 阅读第三方设备
  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"); 
     } 
    } 
} 

在当前设置中,我的UI在测试脚本期间没有响应(通常持续2-3分钟)。

正如你所看到的,我没有使用DataReceived事件。相反,我选择专门调用何时写入/读取串行端口。我这样做的部分原因是因为我需要在写入更多数据之前停止并分析缓冲区响应。有了这种情况,有没有办法仍然多线程这个应用程序?

+1

是的,在工作线程中运行整个RunTest函数。 –

+0

谢谢,我会试试 – Nevets

回答

1

您需要在另一个线程上运行它。

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

我假定

LogMessage(); 

正在访问的用户界面。不允许线程直接访问UI,因此最简单的方法是匿名的。在LogMessage中,你可以做类似

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

原谅我听起来像一个新手(我是),但我会在哪里插入此代码。目前,我正在将button_click事件关闭测试脚本。我会把它放在实际的测试脚本中吗?或者在button_click事件代码中? – Nevets

+1

您可以将其添加到您的点击事件中。你也想要告诉用户在运行时发生了什么。 – Tsukasa

+0

非常感谢。你一直是一个巨大的帮助! – Nevets