I am calling a login() method which handles connection to mysql server and then authenticating a user. Connecting to mysql server takes some time so I want to place a label which shows status of “Loading”. I am doing in it something like this:
private void button_login_Click(object sender, EventArgs e)
{
label_status.Text = "Loading ...";
login();
}
But I dont see label_status text changed to “Loading …”. Instead it shows this status in label_status after login function gets back.
I dont know why is this? Is this some threading issue? Any help would be appreciated.
The UI thread will be blocked for the duration of your event handler. If you want to be able to update the UI you need to perform the long running task in a non-UI thread. The
BackgroundWorkeris specifically designed for doing this. Here is a tutorial on how to use one.You should set the text before starting the
BackgroundWorker, set theDoWorkmethod to executeloginand if there is any UI updates that need to happen after you login, you can call them in theCompletedevent.For smaller cases that don’t require a full BGW solution you can use the Task Parallel Library as it allows the simpler cases to remain simple. Here is the standard model for using the TPL: