简体   繁体   中英

Memory leak with a memory stream

I know this code is far from perfect but in my case this was the only way to do it correctly because im embedding WPF in C#, and when applying text regulary the Spellcheck does not work correctly

So this is my code:

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();

I stress tested this, and it seems like ever about 5 times the script gets ran, it adds about 1 MB ram.

What am i doing wrong, i litterly made everyting i used null, or desposed them.

As I told above in comment you can using , you can try this code. hope this should help.

    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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM