I am currently writing an application that performs 3 basic functions:
My application contains a number of test scripts with each one executing a loop of tests such as:
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");
}
}
}
In the current setup my UI is unresponsive during test scripts (usually lasts 2-3 minutes).
As you can see I am not using a DataReceived
event. Instead I am opting to specifically call out when to write/read through the serial port. Part of the reason I am doing this is because I need to stop and analyze the buffer response before writing more data. With that being the case is there a way to still multithread this application?
You need to run it on another thread.
Thread testThread = new Thread(() => RunTest());
testThread.Start();
I assume
LogMessage();
is accessing the UI. Threading you aren't allowed to access the UI directly so the simplest way is anonymous. In LogMessage you would do something like
this.Invoke((MethodInvoker)delegate { richTextBox.Text = yourVar; });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.