tags:

views:

77

answers:

2

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.

+3  A: 

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

Hans Passant
Yes, it appears to be a threading problem, thanks! I put in a lock and all seems well at the moment.
robbrit
Hmm, locks don't fix this kind of problem, they just postpone it. Is InvokeRequired true?
Hans Passant
Ah, you're right, it doesn't always work. I tested it out and InvokeRequired is false when the control is written to.
robbrit
A: 

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();
        }
Abain