Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从事件处理程序更新富文本框_C#_Wpf - Fatal编程技术网

C# 从事件处理程序更新富文本框

C# 从事件处理程序更新富文本框,c#,wpf,C#,Wpf,我试图在消息到达时从事件处理程序更新富文本框。出于某种原因,富文本框只在所有消息到达后才会更新 我使用的代码: private void OutputMessageToLogWindow(string message) { Application.Current.Dispatcher.BeginInvoke(new Action(() => { outputRichTxtBox.AppendText(messa

我试图在消息到达时从事件处理程序更新富文本框。出于某种原因,富文本框只在所有消息到达后才会更新

我使用的代码:

    private void OutputMessageToLogWindow(string message)
    {




        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            outputRichTxtBox.AppendText(message);
            test.Text = message;
        }));
    }

我认为您的代码不是线程安全的,在并发消息的情况下,某些消息可能不会通过同时执行以下行来更新:

outputRichTxtBox.AppendText(message);
test.Text = message;
因此,为了使其线程安全,我建议在
BeingInvoke
方法中使用
lock

private static readonly object synchLock = new object();

private void OutputMessageToLogWindow(string message)
{
    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
    {
        lock(synchLock)
        {
           outputRichTxtBox.AppendText(message);
           test.Text = message;
        }
    }));
}

尝试同样的事情