c# richtextbox outofmemory

强颜欢笑 提交于 2020-01-04 14:28:21

问题


I have written an app that reads incoming chat(somewhat like an instant messenger), formats it and inserts it into a richtextbox. If you leave the program running long enough you will get an out of memory error. After looking at my code i think this is because i am never trimming the richtextbox. The problem that i'm running into is i don't want to call clear() because i don't want the visible text to disappear. I was thinking maybe i should keep a List with a max size of somthing like 200 lines. This List would keep the most recent chat. If the chat log grows to big, call clear and reinsert the last 200 lines. However, before i implement this thought i would ask if anyone knows of a better solution. Any thoughts?


回答1:


I would probably do the following:

  1. Catch the RichTextBox.TextChanged event
  2. In the handler, check the number of lines (RichTextBox.Lines.Length)
  3. If this exceeds your maximum, remove the first.

Good luck!




回答2:


While I agree with the accepted answer, I wanted to provide a code example to show some clarification:

private void rtbChatWindow_TextChanged(object sender, EventArgs e)
{
    int maxLines = 200;

    if (rtbChatWindow.Lines.Length > maxLines)
    {
         string s = rtbChatWindow.Lines.First();
         rtbChatWindow.Text = rtbChatWindow.Text.Remove(0, s.Length).Trim();
    }
}

Make sure you call Trim() after you remove the text otherwise the first line of text becomes blank space which causes this to not work.



来源:https://stackoverflow.com/questions/4642786/c-sharp-richtextbox-outofmemory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!