AccessViolation occurs in RichTextBox.ScrollToCaret

柔情痞子 提交于 2019-12-10 20:09:57

问题


A hard to track exception is occuring when non-UI threads try to Append their output to RichTextBox UI control in the Main Thread.

This exception occurs at random times, mostly when the threads are calling this method in quick succession. It occurs even in just 2 non-UI threads.

Below is the code of AppendLog method. It is in the Main UI's Form class. I spawn 2 threads and pass them this method as Action<string> logDelegate

I even have the syncobject in place.

  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 : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

  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

回答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());}.



来源:https://stackoverflow.com/questions/10438493/accessviolation-occurs-in-richtextbox-scrolltocaret

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!