Using Invoke to access object in a windows forms/controls thread

Using asynchronous programming might be helpful in making the user's experience better. Asynchronous programming basically includes processing of a heavy operation into a separate thread to avoid the UI freezing and letting the user to perform other operations parallely. In a windows application whenever you try to access a windows forms or controls object from a different thread then you won't be able to do. To handle such kind to scenario, you can use Invoke to access a cross thread object

Suppose you have a function in you form which you want call from a separate thread.

private void UpdateStatus(string statusText)
{
  // Body of the function
}

First of all you need to create a delegate with matching signature of this function

delegate void UpdateStatusInvoker(string statusText)

Now to call this function from a separate thread use Invoke method with parameters

this.Invoke(new UpdateStatusInvoker(UpdateStatus), "Status text");

If you are not sure whether it will be called from a different thread, you can check whether invoke is required.

if (this.InvokeRequired)
{
  this.Invoke(new UpdateStatusInvoker(UpdateStatus), "Status text");
}
else
{
  UpdateStatus("Status text");
}

6 comment(S)


Mexihpoz on Dec 13, 2008 09:57 AM

Thanks!,

sohrab on Oct 28, 2012 06:58 AM

very simple and clear code.
thank you.

diesinker on Dec 12, 2012 02:37 AM

yup simple and easy to understand. thanks very much.

Sony Arouje on Jan 14, 2013 03:45 AM

Thanks for the post. Clear and simple, helped a lot.

Winston on May 15, 2013 02:24 AM

THIS IS AWESOME! You saved me from a HUGE headache, thank you a lot!

Hesam on Apr 28, 2014 12:15 AM

useful and easy to understand. Saved me a lot of time

Leave a comment