【问题标题】:Accelerate add text to a TextBox加速向 TextBox 添加文本
【发布时间】:2014-02-11 10:28:31
【问题描述】:

我有代码将 TexBox 的文本设置为

 textBox1.Text = s;

其中s是一个超过100,000个字符的字符串,在textBox上显示文本需要很长时间。

谁有办法让它更快?

【问题讨论】:

  • 有趣的问题。等待解决方案,:)
  • 文本框对于较长的文本有点慢。尝试改用富文本框。这可能会加快速度。
  • 这是在 Windows 窗体上还是在 XAML 上?
  • @AymanDaoudi : WinForm

标签: c# .net string performance textbox


【解决方案1】:

为此,将s 字符串拆分为多个字符串,并使用AppendText 添加这些子字符串,如果您检查MSDN,您将看到:

AppendText 方法使用户能够在不使用文本连接的情况下将文本附加到文本控件的内容中,当需要许多连接时,可以产生更好的性能

 public string s = "Put you terribly long string here";

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //For responsiveness 
        textBox1.BeginInvoke(new Action(() =>
        {
            //Here's your logic
            for (int i = 0; i < s.Length; i += 1000)
            {
                //This if is just for security
                if (i+1000 > s.Length)
                {
                    //Here's your AppendText
                    textBox1.AppendText(s.Substring(i, s.Length-i));
                }
                else
                {
                    //And it's here as well
                    textBox1.AppendText(s.Substring(i, 1000));
                }
            }
        }));
    }

我使用了 1000 的值,你可以使用 1500 、 2000 ,选择效果更好的那个。 希望这会有所帮助。

更新:

AppendText 适用于 WindowsForms 和 WPF,可惜在 WindowsPhone 和 WinRT 上找不到。所以我认为这个解决方案可能会对你有很大帮助

【讨论】:

  • 我不认为这是 WinForms 的一个选项,但对于 WPF,这是一个很好的解决方案。
  • @Madushan : AppendText 在两者中都可用,你的意思是不是 PerfrmanceWise 选项?
  • 我尝试了这种方法,但它仍然非常非常慢
  • 我的错……对不起。两者都可用。
  • @MaRiO : 是的,你是对的,确实很慢,试试我的更新,现在非常快,我试过了。
【解决方案2】:

break 子字符串中的 s,当您将第一个子字符串传递给文本框时,它将出现在它连接到第二个等之后。 另一种方法是使用循环设置值

for(int i=0;i<s.length; i++)
{
   textBox1.Text += s[i];
 }

这些对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多