AccessViolation 发生在 RichTextBox.ScrollToCaret 中



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

此异常在随机时间发生,主要是在线程快速连续调用此方法时。即使仅在 2 个非 UI 线程中也会发生。

下面是 AppendLog 方法的代码。它位于主 UI 的窗体类中。我生成了 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 : 试图读取或写入受保护的内存。这通常表示其他内存已损坏。

  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:MyAppCodeChartingOfflineAnalyzer.cs:line 339
在这种情况下

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

最新更新