我的设置如下。我有一个带有Log属性的UI线程,用于更新RichTextBox。我有一个非UI线程填充Log属性。非UI线程由Timer控制。我还在UI中有一个更新Log属性的Button。 LogPresenter只是一个格式化消息并将其发送到Log Property的类。
当我更新RichTextBox上的SelectedText属性时,我随机收到一个AccessViolationException。这里是相关的代码
public static class ThreadHelpers
{
public static void InvokeIfRequired(this Control c, Action a)
{
if (c.InvokeRequired)
c.Invoke(a);
else
a();
}
}
public string Log
{
set
{
lock (value)
{
richLog.InvokeIfRequired(() => OnLogMessage(value));
}
}
}
[HandleProcessCorruptedStateExceptions]
private void OnLogMessage(string message)
{
try
{
richLog.SelectionStart = richLog.Text.Length;
var selection = message.Split('-');
var loggingLevel = selection[0].Trim();
switch (loggingLevel)
{
case "Information":
richLog.SelectionColor = Color.SteelBlue;
break;
case "Warning":
richLog.SelectionColor = Color.Goldenrod;
break;
case "Error":
richLog.SelectionColor = Color.DarkRed;
break;
case "SuccessAudit":
richLog.SelectionColor = Color.DarkOliveGreen;
break;
case "FailureAudit":
richLog.SelectionColor = Color.OrangeRed;
break;
default:
richLog.SelectionColor = Color.Silver;
break;
}
richLog.SelectedText = message;
ScrollToBottom();
}
catch (Exception ex)
{
// The lines below just cause cascading fail so I took them out.
//_logPresenter.Fail("Failed to write Log: {0}", message);
//_logPresenter.Error("{0}" + Environment.NewLine + "StackTrace: {0}", ex.Message, ex.StackTrace);
}
}
我得到的确切错误是这样的: 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, EDITSTREAM lParam)
at System.Windows.Forms.RichTextBox.StreamIn(Stream data, Int32 flags)
at System.Windows.Forms.RichTextBox.StreamIn(String str, Int32 flags)
at System.Windows.Forms.RichTextBox.set_SelectedText(String value)
at Namespace.InteractiveServiceForm.OnLogMessage(String message) in c:\projects\Namespace\InteractiveServiceForm.cs:line 127
我尝试了锁,但它没有帮助任何建议将不胜感激。该应用程序现在只是悬挂UI。