scz*_*vos 0 c# out-of-memory richtextbox winforms
我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;
}
Run Code Online (Sandbox Code Playgroud)
一段时间后我得到了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;
}
}
Run Code Online (Sandbox Code Playgroud)
或者将“rtb”存储在静态变量中,这样您就只能使用一个实例。