robbrit
robbrit

Reputation: 17960

.NET TextBox hangs when updating

I'm trying to prepend a string a read-only, multi-line TextBox using the following code:

private void AddText(string text){
  // output is a StringBuilder object
  output.Insert(0, "\r\n");
  output.Insert(0, text);

  this.textBox1.Text = output.ToString();
}

The issue is that sometimes the window ends up just hanging there (even when output is empty, and text is short). I end up having to kill the application to get it running again. Does anybody know how to get around this?

I've tried using a Label instead, however I need it to be scrollable.

Oh, and I'm using .NET 2.0 for compatibility with another app, so I unfortunately can't use any newer features.

Thanks in advance!

EDIT: I've updated the code to look like this:

private delegate void Outputter(string text);

private void Output(string text){
  lock (messageLock){
    string text = text.ToString();
    // output is a StringBuilder instance variable
    output.Insert(0, Environment.NewLine);
    output.Insert(0, text);

    this.textBox1.Text = output.ToString();
  }
}

private void AddText(string text){
  if (this.textBox1.InvokeRequired){
    this.textBox1.Invoke(new Outputter(this.Output), new object[] {text});
  }else{
    Output(text);
  }
}

When InvokeRequired is false, there is no issue - the textbox is updated just fine. When it is true however, it still hangs.

EDIT2: Alright, I figured out a fix. I have to Show() the window in the constructor, where before I was just calling Show() when the first message came in.

Upvotes: 2

Views: 1094

Answers (2)

Abain
Abain

Reputation: 23

I am this form to update the text and working fine for me

private void AddMessageToTextBox(string line)
        {
            List<string> lines = new List<string>();

            lines.Add(line);
            lines.AddRange(txtResult.Lines);
            txtResult.Lines = lines.ToArray();
            this.txtResult.Refresh();
        }

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942089

Classic sign of a threading problem. Test textBox1.InvokeRequired in this code. And delete any assignment to Control.CheckForIllegalCrossThreadCalls you might have.

Upvotes: 3

Related Questions