2014-02-26 49 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