1

On my form, I have a RichTextBox that will be constantly updated with text (chat application). I also have a TextBox where the user types in their text that they want to send.

Anyway, when the RichTextBox is updating, it blocks the UI thread, meaning I cannot type in the TextBox (or use any buttons) until it finishes updating. Likewise, the RTB is blocked while the TextBox handles key presses (which may be a problem if a user is holding down/spamming keys).

What is the recommended way to deal with this?

Here's the relevant code (shortened for brevity, in order of code flow):

private void button1_Click(object sender, EventArgs e) {
    new Thread(new ThreadStart(() => Start())).Start();
}

public void Start() {
    irc = new IrcClient();
    irc.OnRawMessage += new IrcEventHandler(OnRawMessage);
    irc.Listen();
}

void OnRawMessage(object sender, IrcEventArgs e) {
    WriteLine(e.Data.RawMessage);
}

void WriteLine(string line) {
    this.BeginInvoke(new Action(() => richTextBox1.Text += line + "\n"));
    this.BeginInvoke(new Action(() => ScrollToEnd(richTextBox1)));
}
Corey
  • 1,127
  • 4
  • 15
  • 24
  • You might be able to use a web browser control in place of the RichTextBox. I believe most of the logic runs somewhere else. – JoshRoss Feb 12 '11 at 20:15

1 Answers1

3

The only way to prevent the UI from freezing is to never do a large amount of work on the UI thread. I think the problem is here:

richTextBox1.Text += line + "\n"

At first sight this seems like a small amount of work: it looks like you only ask the RichTextBox to append a single line. However, the RichTexBox doesn't see the difference between "append one line" and "refresh everything" if you use it like that because the above code is equivalent to this:

richTextBox1.Text = richtTextBox1.Text + line + "\n"

It has to process the entire string each time. That's why instead of setting the Text property, you should use AppendText.

Wim Coenen
  • 63,995
  • 12
  • 149
  • 237
  • Whoa, I never knew there was a difference. However, when I changed the line, the text updates became faster and snappier, making any UI freezing unnoticeable. – Corey Feb 12 '11 at 20:49