0

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或什么是正确的方法?

4

1 回答 1

5

从调试器中可以看出,获取 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”存储在静态变量中,这样您就只能使用一个实例。

于 2012-09-24T22:30:10.717 回答