I just wrote a simple app to learn multi-threading, and I’m missing something. I start a new thread that performs a relatively lengthy database operation (checking SharePoint permissions on users for a particular site), often up to fifteen seconds. This is how I am creating the thread (removing some extraneous code for simplicity):
private void btnSelectSite_Click(object sender, EventArgs e)
{
strSiteURL = txtSiteURL.Text;
tmrProgressTimer.Interval = 1000;
tmrProgressTimer.Enabled = true;
ThreadStart starter = delegate { LoadUsers(strSiteURL); };
Thread t = new Thread(starter);
t.Start();
t.Join();
cboUsers.Items.Clear();
cboUsers.Items.AddRange(list.ToArray());
tmrProgressTimer.Enabled = false;
}
I am using a delegate to fire off LoadUsers in its own thread, since LoadUsers requires a string. It populates a generic list (“list” in the code) and I later use that to populate a combobox. My understanding is that while this thread is processing, my UI shouldn’t lock up, being as it is on its own thread; however, that has not been the case. None of the UI refreshes until after the thread finishes, and the app is locked up during the thread processing — the timer never even fires, although it should be ticking every second and the database operation is taking up to fifteen. Could someone tell me what I’m doing wrong?
As Yuriy answered, your UI is blocked, waiting for the thread
tto finish its work thanks to the call to :Note: the edited solution provided by Yuriy does not work either, since the combo gets updated from the worker thread, not the UI, as Ego discovered (cross-thread accesses are not allowed).However, if you don’t do that, your code won’t work either, since you seem to be expecting that the
listwas already populated by the worker thread. This most certainly won’t be the case.In order to get back the results to your combo box, you’ll have (in pre-C# 5 days, at least) to do some additional processing when your
LoadUsersmethod returns. Here is a suggestion of how you could implement it:When your thread returns from
LoadUsersyou’ll have to update the combo box. But you cannot do so in a worker thread: it must be done on the original UI thread. To do so, you’ll have to call theInvokemethod provided by yourForm(see MSDN to learn more about invoking), passing it a delegate. Theafterdelegate will be run on the UI thread and all will be well.I’d also add some code to disable the button, so that the user does not start more than one thread. And when the thread invokes
after, you could finish by reenabling the button.And beware of exceptions 🙂