I'm building an app in C# that runs with Excel, the end game is to allow users to click a button on an excel sheet, which then sends some commands down the serial port, and then reads back data.
This is done and works fine.
My question is, how can I check to make sure that no events / functions are being ran on the serialport_DataReceived;
event before the application closes, as if they are then I will get an exception crash -
The I/O operation has been aborted because of either a thread exit or an application request.
So, in a way I need to run some sort of clean up stating that is the serial port is still gathering data, wait until that has finished before closing down.
This is my code so far;
while (!dataCollected)
{
if (data.Contains(carrier)) // If the read data doesn't contain end carriage return, then retry until it does
{
if (data.Contains(resultMessage)) // Check to make sure it has the result message - this guarantees a fully built read data with no missing bytes
{
ParseIncomingDataToExcel(data); // put the string into a specfic excel row
dataCollected = true; // exits out of the while loop
}
}
else // Carriage not found, data loss - try again
{
data = wrench.ReadLine();
}
}
if (dataCollected)
SetControlPropertyValue(button, "Enabled", true); // Invoke to turn the button enabled to true
So basically, you send a command via serial and then get an output. If you try and exit during this process then it will give an exception (I know this will happen, I would rather put the code in to stop it from happening rather then just putting it in a try block
private void Sheet1_Shutdown(object sender, System.EventArgs e)
{
dataCollected = true;
wrench.Close();
}
This makes the program hang when trying to close a connection on the serial port... If I remove the wrench.close - then the above exception is show (As I expected).
--EDIT--
I've tried declaring my boolean values in my while loop to a global volatile type, but I just have a bad feeling with using something like this, seems like a hack (and still doesn't work, just hangs...)