Use Invoke to update user interface from a separate thread

Agosto 30th, 2007

Description: In Windows Forms if you launch a new thread and want to update controls on your form, you must use Invoke. This example updates the Text property of a Label.

Link: http://www.codekeep.net/snippets/3b1cd8c5-cf11-4eb2-b52f-78dccc2d6de9.aspx

------------------------
First create a method to make the UI updates, and define a delegate that
matches the signature of the method.
------------------------
private delegate void setStatusDelegate(string status);

private void setStatus(string status)
{
	lblStatus.Text = status;
}

------------------------
From another thread, you can use the Invoke method of the form to
execute the setStatus method.
------------------------
Invoke(new setStatusDelegate(setStatus), "This is the status text");

  • .NET
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.