2012-09-24 54 views
0

我在很少的方法中使用RichTextBox实例,这些方法正在更改字体,颜色,将图像转换为Rtf格式。WinForms中的OutOfMemory异常RichTextBox

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或最新的正确方法?

+0

你确定RichTextBox给你提供了内存不足的例外吗?你能分享这个异常吗? –

+1

这是没有意义的,除非你在某处有一个死循环 – MUG4N

+0

使用几个小时后会显示异常。我觉得有些东西是留在记忆里的。但我不知道为什么。我试过使用Dispose,using和GC。现在等待它在Process Monitor中执行。 – sczdavos

回答

4

从获得Rtf属性值后,您可以从调试程序得知rtb.IsHandleCreated属性为true。这是一个问题,窗口句柄保持包装控制活着。您必须再次处置控制销毁处理:在一个静态变量

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

或存储“实时出价”,所以你永远只使用一个实例。