c# - RichTextBox.ScrollToCaret 中出现 AccessViolation

标签 c# winforms access-violation

当非 UI 线程尝试将其输出附加到 RichTextBox 时,会发生难以跟踪的异常主线程中的 UI 控件。

此异常随机发生,主要是在线程快速连续调用此方法时。它甚至发生在 2 个非 UI 线程中。

下面是AppendLog方法的代码。它位于主 UI 的 Form 类中。我生成 2 个线程并将此方法作为 Action<string> logDelegate 传递给它们

我什至有同步对象。

  public void AppendLog(string message)
    {
        try
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(this.AppendLog), message);
            }
            else
            {
                lock (_logSyncRoot)
                {

                    if (rtbLog.TextLength > 100000)
                        rtbLog.ResetText();

                    rtbLog.AppendText(message);
                    rtbLog.ScrollToCaret();
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
    }

System.AccessViolationException:试图读取或写入 protected 内存。这通常表明其他内存已损坏。

  at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
  at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
 at System.Windows.Forms.Control.DefWndProc(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
at System.Windows.Forms.RichTextBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, Int32 wParam, Object& editOle)
at System.Windows.Forms.TextBoxBase.ScrollToCaret()
at MyApp.UI.OfflineAnalyzer.AppendLog(String message) in    D:\MyApp\Code\Charting\OfflineAnalyzer.cs:line 339

最佳答案

在这种情况下,最简单的情况是维护一个 Queue<string> queue;例如,如果您有消息列表。随意向队列中添加值。在主窗体线程中,使用计时器组件并在提取值时锁定队列,例如lock (queue) {rtbLog.AppendText(queue.Dequeue());} .

关于c# - RichTextBox.ScrollToCaret 中出现 AccessViolation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10438493/

相关文章:

c# - NHibernate 3.1 与 Linq 的迁移问题

c# - 从 JSON 数组中查找最大值

c# - 如果用户未在 C# 中选择图像,我想在图片框中加载默认图像

c# - 如何将列表计数绑定(bind)到标签

c# - 同时运行两个winform窗口

c++ - 在 Debug模式下访问冲突,但在 Release模式下正常

c# - 使用 System.Diagnostics.Debugger.Break() 比附加到进程有什么好处?

c# - ServiceStack 4 C# 客户端异步调用挂起

c++ - 负数组索引

exception - 禁用 .NET 处理 native 异常