Morning all,
I have an odd behaviour that has just started on some code that has been working for ages. I load a file (from uSD or USB) and parse it to set up some CAN frames. The following routine is called a few times and has been working fine for ages, with the Debug.Print in place. Now it is throwing an exception.
private void setUpTxFrames(FileStream dataFile, ref CANMessage[] txFrames)
{
int n_Tx = (int)(dataFile.ReadByte()); // 1 Byte = number of CAN messages in setup file
txFrames = new CANMessage[n_Tx];
// Index through the setup file and populate the CAN message arrays
for (int i = 0; i < n_Tx; i++)
{
txFrames[i] = new CANMessage();
txFrames[i].period = (dataFile.ReadByte() * 5); // 1st byte per message is period / 5ms
// Don't use this byte
//CANTxMsg[i].MsgData[0].Length = dataFile.ReadByte(); // 2nd byte per message is number of bytes (Length)
// going to discard it...
dataFile.ReadByte(); // 2nd byte per message is number of bytes (Length)
// Next 8 bytes are the CANdata (even if Length < 8)
byte[] _msgData = new byte[8];
int readbytes = dataFile.Read(_msgData, 0, 8);
txFrames[i].setData(_msgData);
// Read next 4 bytes and convert to uint for ArbitrationId (Message address)
uint ArbId = (uint)((dataFile.ReadByte() << 24) + (dataFile.ReadByte() << 16) + (dataFile.ReadByte() << 8) + dataFile.ReadByte());
txFrames[i].setID(ArbId);
// Read period
if (txFrames[i].period == 0)
{ txFrames[i].active = false; }
else
{ txFrames[i].active = true; }
Debug.Print("After CAN message " + i + " : Mem=" + Debug.GC(false));
}
}
I load a file from the uSD, and it enters this routine. Typically, there are about 13 CAN frames, so it will step through the main loop shown 13 times. It goes through the first time with no issues. When it reaches the Debug.Print statement, the Debug.GC(false) appears to trigger the system to dispose of the filestream even though I have not closed it myself yet. Then, when I call the Read on the next time through the loop I get an exception saying that the Filestream has been disposed, and a Watch on the dataFile.length (and other parameters) backs this up.
If I comment out the Debug.GC(false), it all works fine.
Oddly, this never happened before , but I have recently modified the way I sense the uSD card is there (check the GPIO pin instead of a Try Catch around the mount), so maybe that is affecting it.
However, my 2 questions are:
- Should GC dispose of this filestream if I haven’t closed it yet, even if I call Debug.GC?
- If I call Debug.GC(false) I thought this did not force GC, and just return the free memory?
- Are there any settings in Visual Studio that affect GC that I may have inadvertently set/reset that could change this behaviour?
For now, I do not need to print the memory here anyway (it was more of a hangover from a previous project with less memory), so this does not block me, but I would like to understand what is happening and check if I am handling the filestream incorrectly.
Thanks
Nick