简体   繁体   中英

OutOfMemory exception in WinForms RichTextBox

I'm using RichTextBox instances in few methods which are changing font, color, converting images to Rtf format.

public static string ColorText(string text)
{
    System.Windows.Forms.RichTextBox rtb = new System.Windows.Forms.RichTextBox();

    rtb.Text = conversation;

    // find predefined keywords in text, select them and color them

    return rtb.Rtf;
}

After a while I'm getting OutOfMemory Exception. Should I call rtb.Dispose(); ? Or GC.Collect or use using Or whats the right way?

You can tell from the debugger, the rtb.IsHandleCreated property will be true after you obtain the Rtf property value. That's a problem, window handles keep their wrapper control alive. You must dispose the control again to destroy the handle:

public static string ColorText(string text) {
    using (var rtb = new System.Windows.Forms.RichTextBox()) {
        rtb.Text = text;
        return rtb.Rtf;
    }
}

Or store "rtb" in a static variable so you only ever use one instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM