Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.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# 当程序写入WPF文本框时,如何减少高CPU使用率?_C#_.net_Wpf_Performance_Textbox - Fatal编程技术网

C# 当程序写入WPF文本框时,如何减少高CPU使用率?

C# 当程序写入WPF文本框时,如何减少高CPU使用率?,c#,.net,wpf,performance,textbox,C#,.net,Wpf,Performance,Textbox,我开发了小型WPF应用程序,我有以下代码在textbox中编写日志: public void RemoteInfo(string message) { textBox.Dispatcher.BeginInvoke(new Action(delegate () { DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)

我开发了小型WPF应用程序,我有以下代码在textbox中编写日志:

    public void RemoteInfo(string message)
    {
        textBox.Dispatcher.BeginInvoke(new Action(delegate ()
        {
            DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture) + " " + message + Environment.NewLine + textBox.Text;
        }));
    }
我通过以下代码调用此方法:

     Task.Run(() =>
        {
            while (true)
            {
                statusBarWriter.RemoteInfo("Some text");
                Thread.Sleep(100);
            }
        });
当这段代码运行时,CPU使用率至少增加到30%(30%后,我停止程序以防止冻结)

代码有什么问题?如何防止CPU的高使用率


更新第二个代码段是最新的

更改写入方式后,CPU负载降低,现在大约为0-1%:

    textBox.SelectionStart = 0;
    textBox.SelectionLength = 0;
    textBox.SelectedText = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture) + " " + message + Environment.NewLine;

你是在没完没了地运行它吗?新任务的生成是否比更新文本框内容的速度更快?更新的时间会增加,因为你会添加文本,而不会删除一些。你发布的代码不会导致30%的CPU使用率,除非它被敲打,你怎么调用它呢?与其使用无休止的循环睡眠,不如使用Dispatcher。它的勾号事件是在UI线程中触发的,因此您不需要调用BeginInvoke。很抱歉,我粘贴了错误的第二个代码段,现在我更新了它。我像dlatikay说的那样以无休止的循环运行代码,你从一个线程写到UI线程,这将导致大量的上下文切换。使用“BeginInvoke”并不是一个好的设计选择,因为它在引擎盖下使用PostMessage而不是SendMessage。因此,当您使用事件向UI线程发出更改信号时,效果会更好,