2012-09-24 55 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; 
    } 
} 

或存儲「實時出價」,所以你永遠只使用一個實例。