c pound

I reject your reality and substitute my own!
posts - 46, comments - 46, trackbacks - 40

My Links

News

Archives

Image Galleries

Blog Communities

Blog is a stupid word

Lunch Hour

Resources

Arcane Asynchronous Invocation

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

Print | posted on Thursday, January 05, 2006 1:12 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: