Updating GUI from Other Threads in C#

I’ve been meaning to write this down for a while. There is a really easy way of updating controls and generally updating the GUI of your main thread from another thread using BeginInvoke.

Create a global delegate for your Form class eg:

public delegate void InvokeDelegate(string input);

This means the delegate takes in a single argument (a string in this case). Next create a method to call to update the controls or do anything really. My method just appends text to a textbox:

public void UpdateLog(string input)

Now when you want to call this method from threads other than the main thread you create an object array, put in your input variables and use BeginInvoke to call your delegate which in turn calls your method:

object[] obj = new object[1];
obj[0] = “text to append to my log textbox”
textboxLog.BeginInvoke(new InvokeDelegate(UpdateLog), obj);

6 thoughts on “Updating GUI from Other Threads in C#

  1. Thank you very mutch for your help, I have seeked so long about this problem and don’t found somethings helpfull, as over hier. I wish you and your families a Merry Christmas and the very best for next year, especially health, luck and good business!!!

    V. Hakobyan, Germany 19.12.2008

  2. Easy enough, but somethings missing. If you run it and kill the host app while the thread is still running, it locks up.

    if(th.IsAlive){ th.Abort(); } to an overridden OnClosing method will prevent this issue.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>