【问题标题】:Unresponsive UI when too fast and too much data needs to be updated当速度太快且需要更新太多数据时,UI 无响应
【发布时间】:2011-04-15 14:11:37
【问题描述】:

我做了一个控件,可以将来自不同线程的消息记录到屏幕上。它使用富文本框来显示格式化的文本。

当有 20 个线程每 200-250 毫秒附加其消息时,主 UI 会在一段时间内无响应,并且在处理等待的消息后,UI 会再次开始响应。当线程运行时,窗口的移动并不顺畅。

将消息写入富文本框与锁同步。

您有什么建议可以提高性能?我打算运行 100 个线程。


这是我的代码。我将控制台输出重定向到它,它会记录所有正在发生的事情并在富文本框中以格式化的形式显示。

public void RedirectStandardOutput()
        {
            Console.SetOut(ConsoleStream);

            System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(Console.Out));
            System.Diagnostics.Debug.AutoFlush = true;
        }

控制台重定向后所有 Console.WriteLine("bla bla");被写入屏幕。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CoreLib.Parsers;

namespace ConsoleWidget
{
    public class ConsoleStream : System.IO.TextWriter
    {
        private readonly object _textBoxLock = new object();

        public RichTextBox TextBox { get; set; }
        public List<TextFormat> TextFormatList { get; set; }

        public bool AutoClear { get; set; }
        public int AutoClearLength { get; set; }
        public bool AutoSave { get; set; }
        public string AutoSaveDir { get; set; }


        public ConsoleStream()
        {
            TextFormatList = new List<TextFormat>();
        }

        public void AppendText(string text)
        {
            if (TextBox == null) return;

            var textLength = TextBox.TextLength;

            if (AutoClear && textLength > AutoClearLength)
            {
                if (AutoSave)
                {
                    var dir = string.Format(@"{0}\{1}\{2}", Environment.CurrentDirectory, AutoSaveDir, CoreLib.Extensions.DateTimeExtensions.DateTimeNowDir);

                    if (!System.IO.Directory.Exists(dir))
                        System.IO.Directory.CreateDirectory(dir);

                    var path = string.Format(@"{0}\{1}.log", dir, CoreLib.Extensions.DateTimeExtensions.GetDateTimeNowFileName);

                    TextBox.SaveFile(path);
                }

                TextBox.Clear();
            }

            TextBox.AppendText(text);

            // Format text.
            foreach (var textFormat in TextFormatList)
            {
                int beginIndex;
                int length;

                if (textFormat.GetFormatProperties(text, out beginIndex, out length))
                {
                    // RichTextBox counts newline "\r\n" which is double char as single char.
                    // Causes shifting in selection starts. The lines below count the "\r" chars before the beginIndex.
                    var leftText = text.Substring(0, beginIndex);
                    var newLineCount = leftText.Count(c => c == '\r');

                    TextBox.SelectionStart = textLength + beginIndex - newLineCount;
                    TextBox.SelectionLength = length;
                    if (!textFormat.Color.IsEmpty)
                        TextBox.SelectionColor = textFormat.Color;
                    if (textFormat.Font != null)
                        TextBox.SelectionFont = textFormat.Font;
                }
            }

            TextBox.ScrollToCaret();
        }

        public void Clear()
        {
            lock (_textBoxLock)
            {
                TextBox.Clear();
            }
        }

        public int TextLength
        {
            get
            {
                lock (_textBoxLock)
                {
                    return TextBox.TextLength;
                }
            }
        }

        public void SaveAs(string path)
        {
            lock (_textBoxLock)
            {
                TextBox.SaveFile(path);
            }
        }

        public override Encoding Encoding
        {
            get { return Encoding.Default; }
        }

        public override void Write(string value)
        {
            if (TextBox == null) return;

            var action = (Action)(() => AppendText(value));

            lock (_textBoxLock)
            {
                if (TextBox.InvokeRequired)
                    TextBox.BeginInvoke(action);
                else
                    action();
            }
        }

        public override void WriteLine()
        {
            Write(NewLine);
        }

        public override void WriteLine(string value)
        {
            Write(value);
            WriteLine();
        }
    }
}

【问题讨论】:

  • 你能分享更新文本框的代码吗?
  • 你的跨线程写得怎么样?您是在使用 Control.Invoke、Control.BeginInvoke,还是在 UI 线程上轮询消息?
  • 您可能还想考虑使用富文本框以外的其他方式来显示数据。我从来没有使用过,所以我只是猜测,但我怀疑随着 TextBox 中文本大小的增加,添加文本会变得越来越慢。只是一个想法....
  • 对我来说,自从在 Windows 7 上运行我的应用程序后,这个问题就突然开始了。在 XP 上没问题 :(

标签: c# multithreading winforms


【解决方案1】:

让他们写入缓冲区 RichTextBox(实际上不是表单的一部分),并且每隔 250 毫秒左右将缓冲区附加到 UI RichTextBox。

【讨论】:

  • 一种不同于由 UI 线程控制的缓冲区的缓冲区绝对是这里的方法。然后 UI 可以有一个 Timer 触发事件以更新缓冲区中的可见组件。
  • 这次我需要自己管理对象的状态。需要保存新消息并每 250 毫秒附加一次。
【解决方案2】:

让您的工作线程将它们的数据添加到某种队列/列表中,然后让主线程每秒/半秒从新数据存储中添加一批新数据(调整以适应您的流程)。

像这样基本的东西可能会很好:

    public class DataStore<T>{
    private object _lock = new object();
    private List<T> _data = new List<T>();
    public void Add(T data){
        lock (_lock){
            _data.Add(data);
        }
    }

    public T[] TakeWork(){
        T[] result; 
        lock (_lock){
            result= _data.ToArray(); 
            _data.Clear();
        }
        return result;
    }
}

只需创建一个 DataStore 并让您的工作线程使用 Add 函数添加要显示的工作,然后执行

      foreach (var s in _dataStore.TakeWork()){
            richTextBox.AppendText(s);                  
        }

在 System.Windows.Forms.Timer 事件中。不过,您可能还想修剪富文本框文本,因为如果您整天不停地输入数据,您的应用程序就会开始变慢....

【讨论】:

  • 您好,我在这里可能有点晚了,但是我遇到了将大量数据注入富文本框的问题,UI 变得无响应。将数据添加到 RTB 发生在单独的线程中。任何线索将不胜感激。
【解决方案3】:

也许您可以尝试使用线程池或任务来更好地管理您的线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2018-04-07
    • 2018-11-28
    • 2010-12-10
    • 1970-01-01
    • 2019-01-28
    相关资源
    最近更新 更多