Search code examples
c#.netwpfperformancetextbox

How to decrease high CPU usage while program writes to WPF textbox?


I develop small WPF app and I have the following code to write logs in 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;
        }));
    }

I call this method from the following code:

     Task.Run(() =>
        {
            while (true)
            {
                statusBarWriter.RemoteInfo("Some text");
                Thread.Sleep(100);
            }
        });

While this code is running CPU usage increases at least to 30% (after 30% I stop the program to prevent freezing).

What's wrong with the code and how can I prevent high CPU usage?

UPDATE second code snippet is up to date


Solution

  • After changing writing way, CPU load decreases and now it is about 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;