带有内存流的内存泄漏

时间:2019-03-22 01:54:15

标签: c#

我知道这段代码远非完美,但就我而言,这是唯一的  正确执行此操作的方法,因为将WPF嵌入C#中,以及何时  定期应用文本,拼写检查无法正常工作

这是我的代码:

RichTextBox temphotfix = new RichTextBox();
temphotfix.Font = new Font(temphotfix.Font.Name, 14);
System.Windows.Documents.TextRange range = new System.Windows.Documents.TextRange(omschrijving.Document.ContentStart, omschrijving.Document.ContentEnd);
temphotfix.Text = oms;
string temp = temphotfix.Rtf;
byte[] byteArray = Encoding.ASCII.GetBytes(temp);
MemoryStream stream = new MemoryStream(byteArray);
range.Load(stream, DataFormats.Rtf);
range = null;
temp = null;
byteArray = null;
temphotfix.Dispose();
stream.Dispose();

我对此进行了压力测试,似乎脚本运行了大约5次,它增加了大约1 MB的内存。

我在做什么错了,我随便把我使用过的所有内容都设为null或废弃了。

1 个答案:

答案 0 :(得分:-1)

正如我上面在评论中告诉您的,您可以using,可以尝试以下代码。希望这会有所帮助。

    using (RichTextBox temphotfix = new RichTextBox())
    {
        temphotfix.Font = new Font(temphotfix.Font.Name, 14);
        System.Windows.Documents.TextRange range = new System.Windows.Documents.TextRange(omschrijving.Document.ContentStart, omschrijving.Document.ContentEnd);
        temphotfix.Text = oms;
        string temp = temphotfix.Rtf;
        byte[] byteArray = Encoding.ASCII.GetBytes(temp);
        using (MemoryStream stream = new MemoryStream(byteArray))
        {
            range.Load(stream, DataFormats.Rtf);
        }
        range = null;
        temp = null;
        byteArray = null;
        //temphotfix.Dispose();
        //stream.Dispose();
    }