Reputation: 11
I read data from serialport in byte[] then show in hex string in richtexbox.
private string ByteArray_to_Hex(byte[] data) {
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data) {
buffer_log.Add(b); // save data in buffer to write to file
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
}
GC.Collect();
return sb.ToString().ToUpper();
}
private void Log(string msg) {
try {
Richtexbox.Invoke(new EventHandler(delegate {
Richtexbox.AppendText(msg);
if (Richtexbox.Text.Length > 1000000) {
// seem to slow when comparing to amount of data reading
Richtexbox.Select(10000, 950000);
Richtexbox.SelectedText = "";
}
}));
} catch {
}
}
private void PLay_Click()
{
Log(ByteArray_to_Hex(data_come_from_serialport);
}
It consume lots of memory since there are lots of texts. But when I call
private void menu_Clear_Click(object sender, EventArgs e) {
Richtexbox.Clear();
buffer_log.Clear();
GC.Collect();
}
It isn't release memory, still consume lots of memory in ram. What 's the best way to release these memory?
since it's the best way. What is this problem. I describe my problem I had: This app always has systemoutofmemory exception when runing for 1 hour. If I run this app for 55 minutes then call Clear method, it only work for 5 minutes and has systemoutofmemory exception. Can someone explain this ?
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!SerialPort.IsOpen)
{
return;
}
if (flag_stop)
{
return;
}
int bytes = SerialPort.BytesToRead;
byte[] buffer = new byte[bytes];
SerialPort.Read(buffer, 0, bytes);
Log(ByteArray_to_Hex(buffer));
}
update way to read data from serialport.
Upvotes: 0
Views: 2294
Reputation: 2079
You should not need to do anything. Thats the magic of managed code.
But you want to try to trigger the garbage collector you can use.
GC.Collect();
GC.WaitForPendingFinalizers();
But read this first and then this and finally the dry boring msdn text
Upvotes: 2