简体   繁体   English

WinForms RichTextBox中的OutOfMemory异常

[英]OutOfMemory exception in WinForms RichTextBox

I'm using RichTextBox instances in few methods which are changing font, color, converting images to Rtf format. 我在几种方法中使用RichTextBox实例,这些实例可以更改字体,颜色,将图像转换为Rtf格式。

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. 一段时间后,我收到OutOfMemory异常。 Should I call rtb.Dispose(); 我应该调用rtb.Dispose(); ? Or GC.Collect or use using Or whats the right way? GC.Collect或使用using或什么的正确方法?

You can tell from the debugger, the rtb.IsHandleCreated property will be true after you obtain the Rtf property value. 您可以从调试器得知,获取Rtf属性值后,rtb.IsHandleCreated属性将为true 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. 或将“ rtb”存储在静态变量中,以便仅使用一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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