3

当非 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 : 试图读取或写入受保护的内存。这通常表明其他内存已损坏。

  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
4

1 回答 1

1

The easiest situation in scenarios like this is to maintain a Queue<string> queue; if you have a list of messages for example. Add values to to the queue at will. In the main form thread, use a timer component and lock the queue while pulling out values e.g. lock (queue) {rtbLog.AppendText(queue.Dequeue());}.

于 2012-05-09T03:01:38.587 回答