如何在程序写入 WPF 文本框时减少 CPU 的高使用率?
How to decrease high CPU usage while program writes to WPF textbox?
我开发了小型 WPF 应用程序,我有以下代码可以在文本框中写入日志:
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 使用率过高?
UPDATE 第二个代码片段是最新的
改写方式后,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;
我开发了小型 WPF 应用程序,我有以下代码可以在文本框中写入日志:
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 使用率过高?
UPDATE 第二个代码片段是最新的
改写方式后,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;