How to update textbox on GUI from another thread [duplicate]

You need to either use BackgroundWorker, or Control.Invoke/BeginInvoke. Anonymous functions – either anonymous methods (C# 2.0) or lambda expressions (C# 3.0) make this easier than it was before.

In your case, you can change your code to:

public bool AddUser(string user, RichTextBox textBox1, List listBox1)
{
    MethodInvoker action = delegate
         { textBox1.Text += "Connected to server... \n"; };
    textBox1.BeginInvoke(action);
}

A few things to note:

  • To conform with .NET conventions, this should be called AddUser
  • You don’t need to pass the textbox or listbox by reference. I suspect you don’t quite understand what ref really means – see my article on parameter passing for more details.
  • The difference between Invoke and BeginInvoke is that BeginInvoke won’t wait for the delegate to be called on the UI thread before it continues – so AddUser may return before the textbox has actually been updated. If you don’t want that asynchronous behaviour, use Invoke.
  • In many samples (including some of mine!) you’ll find people using Control.InvokeRequired to see whether they need to call Invoke/BeginInvoke. This is actually overkill in most cases – there’s no real harm in calling Invoke/BeginInvoke even if you don’t need to, and often the handler will only ever be called from a non-UI thread anyway. Omitting the check makes the code simpler.
  • You can also use BackgroundWorker as I mentioned before; this is particularly suited to progress bars etc, but in this case it’s probably just as easy to keep your current model.

For more information on this and other threading topics, see my threading tutorial or Joe Albahari’s one.

Leave a Comment

tech