我目前正在寫,執行3種基本功能的應用程序:多線程的串行端口C#
- 發送命令到第三方設備
- 閱讀第三方設備
- 分析響應字節響應和寫分析的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
事件。相反,我選擇專門調用何時寫入/讀取串行端口。我這樣做的部分原因是因爲我需要在寫入更多數據之前停止並分析緩衝區響應。有了這種情況,有沒有辦法仍然多線程這個應用程序?
是的,在工作線程中運行整個RunTest函數。 –
謝謝,我會試試 – Nevets