Dear all, I'm developing a C# multithreaded application, based on (http://www.codeproject.com/useritems/GpsTracer.asp) which starts a thread whose duty is to wait on the serial port and whenever it receives something, to process it accordingly. The ony difference from my code to the one in the web page is that I wait indefinitely until a DataReceivedEvent pulls the thread out of the sleep state, since once the serial port is open, it receives a continuous stream of data, and there is no need to wait a certain amount of ms.
My question are:
1) what is the best way to stop smoothly such a mechanism without leaving the port open or the thread active, so that I can restart the thread without the ned of closing and restarting the application
2) a .DiscardInBuffer call before the closing of the port would ease the process
Many thanks in advance for your attention
Paolo
//------------------------- Start Routine --------------------------------
public void start(){
try{
if (myThread == null){
if (mySerialPort == null){
mySerialPort =
new System.IO.Ports.SerialPort(sSerialPort);InitializeSerialPort();
}
myThread =
new Thread(myThreadCore);}
bThreadRunning =
true;myThread.Start();
}
catch (Exception ex){
ex.ToString();
MessageBox.Show("Serialfeeder.start(): " + ex.Message + "\n" + ex.InnerException);}
}
//------------------------- Stop Routine --------------------------------
public void stop()
{
try
{
bThreadRunning =
false; Thread.Sleep(500);mySerialPort.Close();
Connected =
false; if (myThread != null){
myThread.Abort();myThread =
null;}
}
catch (Exception ex){
ex.ToString();
MessageBox.Show("Serialfeeder.stop(): " + ex.Message + "\n" + ex.InnerException);}
}
//------------------------- Thread core Routine --------------------------------
private void myThreadCore(){
int iBytes2Read = 0;try
{
if (!mySerialPort.IsOpen)mySerialPort.Open();
Connected =
true; while (bThreadRunning){
iBytes2Read = mySerialPort.BytesToRead;
if (iBytes2Read > 0){
// Create a byte array buffer to hold the incoming data byte[] buffer1 = new byte[iBytes2Read]; // Read the data from the port and store it in our buffermySerialPort.Read(buffer1, 0, iBytes2Read);
dataReceived(
ref buffer1);}
Thread.Sleep(0);}
ThreadEnding =
true;}
catch (Exception ex){
ex.ToString();
MessageBox.Show("Serialfeeder.ThreadCore(): " + ex.Message + "\n" + ex.InnerException);}
}