C# RichEditBox 性能极慢(加载 4 分钟)

标签 c# winforms performance richtextbox

C# 中的RichEditBox 控件(我使用的是VS 2005)性能不佳。我将一个 2.5 MB 的 RTF 文件和 45.000 行彩色文本加载到控件中,这需要 4 分钟。我将相同的 RTF 加载到 Windows XP 写字板的 RTF 控件中,它在 2 秒内加载。

写字板的执行速度比我的应用程序快 120 倍。

这是什么原因,我该如何解决?

最佳答案

我下载了写字板的源代码(http://download.microsoft.com/download/4/0/9/40946FEC-EE5C-48C2-8750-B0F8DA1C99A8/MFC/ole/wordpad.zip.exe),它的性能同样最差(4 分钟)。但是这个示例是旧版本的写字板。

因此,Microsoft 在过去几年改进了写字板中 .NET 框架中缺失的所有内容。

最后我找到了解决方案:

.NET 框架使用 RichEdit20W 类作为 Richedit 控件,旧的写字板也是如此。而Windows XP的写字板使用的是经过微软高度改进的新RichEdit50W。

那么如何告诉 .NET 框架使用 RichEdit50W 而不是 RichEdit20W 呢?

这非常简单:从 RichTextBox 派生一个类并为 LoadLibary 编写一个托管包装器。

类 RichEdit50W 由自 Windows XP SP1 起可用的 MsftEdit.dll 创建。我实现了 RichEdit20W 的回退,以应对极少数情况,即有人仍应使用没有服务包的 XP。

而且有效!

/// <summary>
/// The framework uses by default "Richedit20W" in RICHED20.DLL.
/// This needs 4 minutes to load a 2,5MB RTF file with 45000 lines.
/// Richedit50W needs only 2 seconds for the same RTF document !!!
/// </summary>
protected override CreateParams CreateParams
{
    get
    {
        CreateParams i_Params = base.CreateParams;
        try
        {
            // Available since XP SP1
            Win32.LoadLibrary("MsftEdit.dll"); // throws

            // Replace "RichEdit20W" with "RichEdit50W"
            i_Params.ClassName = "RichEdit50W";
        }
        catch
        {
            // Windows XP without any Service Pack.
        }
        return i_Params;
    }
}

注意:另见 http://msdn.microsoft.com/en-us/library/windows/desktop/bb787873%28v=vs.85%29.aspx

public class Win32
{
    [DllImport("kernel32.dll", EntryPoint="LoadLibraryW", CharSet=CharSet.Unicode, SetLastError=true)]
    private static extern IntPtr LoadLibraryW(string s_File);

    public static IntPtr LoadLibrary(string s_File)
    {
        IntPtr h_Module = LoadLibraryW(s_File);
        if (h_Module != IntPtr.Zero)
            return h_Module;

        int s32_Error = Marshal.GetLastWin32Error();
        throw new Win32Exception(s32_Error);
    }
}

关于C# RichEditBox 性能极慢(加载 4 分钟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18668920/

相关文章:

c# - 操作 XML 文档的属性

c# - 在多页上打印 c#

javascript - 如何在javascript中找到谁在吃掉我的内存

C# WinForms - 根据数据绑定(bind) datagridview 中另一个组合框的值过滤一个组合框

c# - 什么时候并行提高性能

ruby-on-rails - 我怎样才能弄清楚为什么我的 JRuby Rails 应用程序需要很长时间才能提供页面?

c# - 自动 INotifyPropertyChanged

c# - 窗体关闭时如何停止用户控件上的线程

c# - 续-车牌检测

.net - 当我调整标签的大小时,代码垃圾会在新的空白区域短暂显示