Say you want to call a method on a control on your form from a thread... For example, you might want to populate a ListBox with a lot of data or with data from a really slow data source. In these cases you'll probably be using a seperate thread to get the data because it's generally a Bad Idea to block (freeze) your UI while you wait for all the data to come in. Especially if the data is of an indeterminate length. So, one way to get at that ListBox from a seperate thread it is to use Control.Invoke:
private void StartAsynchLoad()
{
this.lstDatabases.Items.Clear();
//load the databases asynchronously
Thread t = new Thread(new ThreadStart(LoadDatabasesThread));
t.Start();
}
private void LoadDatabasesThread()
{
//load the databases into the listbox
string dataSource = this.txtServer.Text;
string [] names = DataAccess.Instance.GetDatabases(dataSource);
foreach(string name in names)
{
this.Invoke(new AddItemDelegate(AddItem), new object[]{name});
}
}
private delegate void AddItemDelegate(string text);
private void AddItem(string text)
{
this.lstDatabases.Items.Add(text);
}