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

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

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

最佳答案

我遇到了类似的问题,不断创建富文本框控件可能会导致一些问题。如果您在大量数据上重复执行此方法,您将遇到的另一个大问题是您的 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 的持续增长。

关于c# - 在 VC++ 项目中使用 C# DLL 的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18733608/

相关文章:

c# - 如何用C#设置默认浏览器主页(IE)?

c# - 加载图像显示 ASP.NET 中的所有服务器端请求以及客户端请求

c++ - 在 C++ 中使用文本文件进行身份验证

c++ - 用编译器强制第一个实例

c# - 如何获取枚举的基础值

c# - WPF 双向绑定(bind) XML

c++ - 从 BYTE 数组中读取 32 位整数。 VC++

c++ - 将在一个类中创建的 multimap 数据传递给另一个类

visual-studio-2008 - Microsoft 增量链接器已停止工作

c# - 如何以最佳方式使用表达式树获取和设置属性?