繁体   English   中英

VC ++项目中使用C#DLL的内存泄漏

[英]Memory Leaks using C# DLL in VC++ Project

我们已经在C#中创建了一个DLL,以使用System.Windows.Forms.RichTextBox读取RTF文件。 收到RTF文件名后,它将返回文件中没有属性的纯文本。

提供的代码如下。

namespace RTF2TXTConverter
{
    public interface IRTF2TXTConverter
    {
         string Convert(string strRTFTxt);

    };

    public class RTf2TXT : IRTF2TXTConverter
    {
        public string Convert(string strRTFTxt)
        {
            string path = strRTFTxt;

            //Create the RichTextBox. (Requires a reference to System.Windows.Forms.)
            System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox();

            // Get the contents of the RTF file. When the contents of the file are   
            // stored in the string (rtfText), the contents are encoded as UTF-16.  
            string rtfText = System.IO.File.ReadAllText(path);

            // Display the RTF text. This should look like the contents of your file.
            //System.Windows.Forms.MessageBox.Show(rtfText);

            // Use the RichTextBox to convert the RTF code to plain text.
            rtBox.Rtf = rtfText;
            string plainText = rtBox.Text;

            //System.Windows.Forms.MessageBox.Show(plainText);

            // Output the plain text to a file, encoded as UTF-8. 
            //System.IO.File.WriteAllText(@"output.txt", plainText);

            return plainText;
        }
    }
}

Convert方法从RTF文件返回纯文本。 在VC ++应用程序中,每次加载RTF文件时,内存使用情况都会继续

越来越多。 每次迭代后,内存使用量将增加1 MB。

使用后是否需要卸载DLL,然后再次为新的RTF文件加载? RichTextBox控件是否始终保留在内存中? 或任何其他原因。

我们已经尝试了很多,但找不到任何解决方案,这方面的任何帮助将是巨大的帮助。

我遇到了类似的问题,不断创建Rich Text Box控件可能会引起一些问题。 如果您对大量数据重复执行此方法,则会遇到另一个大问题,即rtBox.Rtf = rtfText;需要花费很长时间rtBox.Rtf = rtfText; 这行代码是在第一次使用控件时完成的(在后台设置了一些延迟加载,直到您第一次设置文本时才会发生)。

解决方法是将控件重新用于后续调用,这样您只需支付一次昂贵的初始化费用。 这是我使用的代码的副本,当时我在多线程环境中工作,因此我们实际上使用ThreadLocal<RichTextBox>来旧化控件。

//reuse the same rtfBox object over instead of creating/disposing a new one each time ToPlainText is called
static ThreadLocal<RichTextBox> rtfBox = new ThreadLocal<RichTextBox>(() => new RichTextBox());

public static string ToPlainText(this string sourceString)
{
    if (sourceString == null)
        return null;

    rtfBox.Value.Rtf = sourceString;
    var strippedText = rtfBox.Value.Text;
    rtfBox.Value.Clear();

    return strippedText;
}

查看是否重新使用线程本地富文本框是否会阻止每次调用持续增长1MB。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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