HI,
I am working with FEZ cobra. My application is to get sensor data periodically from Rs232 ports. I have made a class ComAccess to open, write and read from Rs232 port. I have used interrupt based reading in the class. I am creating two object of this class from another class and open two Rs232 ports for communication.
This code works properly. I am sending commands through Write method of ComAccess class and getting response in interrupt.
My problem is, after random time interval, GC executes and I am not getting response from one Rs232 port. Another port is working properly and getting data. I have check the status with the help of oscilloscope and found that signals at RX and TX pins are coming, but didnt get response in code through interrupt function.
The Code for ComAccess class is as under.
public class COMAccess
{
private string PortName;
private int Brate;
private int Stopbit;
private int parity;
private SerialPort serialport = null;
string ClsName = "COMAccess";
string ProsName = "";
string Data = "";
string Fnlstr = "";
public COMAccess()
{
}
public bool OpenPort(string Pname, string Brate, bool flgDataRec)
{
this.serialport = new SerialPort(Pname, Int32.Parse(Brate));
this.serialport.Open();
if (flgDataRec == true)
{
this.serialport.DataReceived += new SerialDataReceivedEventHandler(serialport_DataReceived);
}
return true;
}
private void serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int readcount = serialport.BytesToRead;
byte[] rx_byte = new byte[readcount];
readcount = serialport.Read(rx_byte, 0, readcount);
char[] rechar = Encoding.UTF8.GetChars(rx_byte);
string RecData = "";
RecData = new string(rechar);
}
public bool WritePortData(string sendprotocol)
{
byte[] Buffer = Encoding.UTF8.GetBytes(sendprotocol);
this.serialport.Write(Buffer, 0, Buffer.Length);
//Thread.Sleep(500);
return true;
}
}
If GC happens and you lose COM object response, then the likely cause is your object being discarded but you don’t know it yet. Something goes out of scope, stays around for some random time, then GC cleans it up and the event handler (it’s not an interrupt, really :)) no longer talks. That’s what I’d be looking for.
Thanks Brett. I can understand that GC cleans up the event handler, but what i am not getting is, why only one object’s only eventhandler is cleans up.
I have two object of same class and i have declare them in same pattern. After GC executes, One object work properly and in another object’s only “SerialDataReceivedEventHandler” is not getting response. The other methods of that object works properly like serial write method.
For trial an error, i have remove the “SerialDataReceivedEventHandler” from one object and getting data from serial read method and it works properly in overnight test though GC executes in between.