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

时间:2013-09-11 05:53:56

标签: c# visual-c++

我们在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控件是否始终保留在内存中?或任何其他原因......

我们已经尝试了很多,但我们找不到任何解决方案。在这方面的任何帮助都会有很大的帮助。

1 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,不断创建Rich Text Box控件会导致一些问题。如果您在大量数据上重复执行此方法,您将遇到的另一个大问题是,您的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;
}

查看是否重新使用线程本地Rich Text Box将停止每次调用的持续1MB增长。