繁体   English   中英

WinForms RichTextBox中的OutOfMemory异常

[英]OutOfMemory exception in WinForms RichTextBox

我在几种方法中使用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;
}

一段时间后,我收到OutOfMemory异常。 我应该调用rtb.Dispose(); GC.Collect或使用using或什么的正确方法?

您可以从调试器得知,获取Rtf属性值后,rtb.IsHandleCreated属性将为true 这是一个问题,窗口句柄使它们的包装器控件保持活动状态。 必须再次配置该控件以销毁该句柄:

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

或将“ rtb”存储在静态变量中,以便仅使用一个实例。

暂无
暂无

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

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