How Can I Prevent RichTextBox Append which Can Cause OutOfMemory?
My Objective is keep logs line by line with RichtextBox control, But I am worry that when the lines reach to certain point , my window form will be hung or run of out memory..
Can any one show me how can i prevent this will happen, I have in mind maybe limit 300 lines with FIFO , or 500 lines then empty and refresh again..However i am not sure How Can i implement this.
void WriteLog(string txt)
{
richTextBox1.AppendText(txt + Environment.NewLine);
richTextBox1.HideSelection = false;
richTextBox1.SelectionStart = richTextBox1.Tex开发者_Python百科t.Length;
}
If you want to delete lines than try to use this
void WriteLog(string txt)
{
if(richTextBox1.Lines.Count() == 100)
{
DeleteLine(0);
}
richTextBox1.AppendText(txt + Environment.NewLine);
richTextBox1.HideSelection = false;
richTextBox1.SelectionStart = richTextBox1.Text.Length;
}
private void DeleteLine(int a_line)
{
int start_index = richTextBox1.GetFirstCharIndexFromLine(a_line);
int count = richTextBox1.Lines[a_line].Length;
// Eat new line chars
if (a_line < richTextBox1.Lines.Length - 1)
{
count += richTextBox1.GetFirstCharIndexFromLine(a_line + 1) -
((start_index + count - 1) + 1);
}
richTextBox1.Text = richTextBox1.Text.Remove(start_index, count);
}
try this code to remove last line and then append text then you'll have just 300lines limit:
private void RemoveLastLineAfter300()
{
if(richTextBox1.TextLength != 0)
{
int totalCharacters = richTextBox1.Text.Trim().Length;
int totalLines = richTextBox1.Lines.Length;
string lastLine = richTextBox1.Lines[totalLines - 1] + "\n";
string copyOfLastLine = richTextBox1.Lines[totalLines - 1];
if(totalLines > 300)
{
string newstring = richTextBox1.Text.Substring(0, totalCharacters - lastLine.Length);
richTextBox1.Text = newstring;
}
}
}
And if you want to clear text(if I undertood correctly) after 500lines just check on TextChanged event
if(richTextBox1.Lines.Length > 500)
richTextBox1.Text = string.Empty;
I hope this helps you.
精彩评论