Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with C# multiline textbox memory usage

Tags:

c#

I am using a multiline text box in C# to just log some trace information. I simply use AppendText("text-goes-here\r\n") as I need to add lines.

I've let this program run for a few days (with a lot of active trace) and I noticed it was using a lot of memory. Long story short, it appears that even with the maxlength value to something very small (256) the content of the text box just keeps expanding.

I thought it worked like a FIFO (throwing away the oldest text that exceeds the maxlength size). It doesn't, it just keeps increasing in size. This is apparently the cause of my memory waste. Anybody know what I'm doing wrong?


Added a few hours after initial question... Ok, I tried the suggested code below. To quickly test it, I simply added a timer to my app and from that timer tick I now call a method that does essentially the same thing as the code below. The tick rate is high so that I can observe the memory usage of the process and quickly determine if there is a leak. There wasn't. That was good; however, I put this in my application and memory usage did not change (still leaking). That sure seems to imply that I have a leak somwehere else :-( however, if I simply add a return at the top of that method, the usage drops back to stable. Any thoughts on this? The timer-tick-invoked code did not accumulate memory but my real code (same method) does. The difference is that I'm calling the method from a variety of different places in the real code. Can the context of the call affect this somehow? (note, if it isn't already obvious, I'm not a .NET expert by any means)...

like image 669
Ed. Avatar asked Oct 12 '22 12:10

Ed.


2 Answers

TextBox will allow you to append text regardless of MaxLength value - it's only used to control user entry. You can create a method that will be adding new text after verifying that maxlength is not reached, and if it is, just remove x lines from the beginning.

like image 120
Andrey Avatar answered Oct 16 '22 09:10

Andrey


You could use a simple function to append text:

int maxLength = 256;
private void AppendText(string text)
{
     textBox1.AppendText(text);
     if(textBox1.Text.Length > maxLength)
       textBox1.Text = textBox1.Text.Substring(textBox1.Text.Length - maxLength);
}
like image 29
Varun Chatterji Avatar answered Oct 16 '22 09:10

Varun Chatterji