I thought I understood that in order for a separate thread to make changes to the GUI in a winforms application, the method needed to be invoked. However, I've written a method to asynchronously populate a combobox, and it shows me that there's more to the story.
Here is the relevant code, with company info omitted:
private List<string> ids = new List<string>();
private BindingSource bindingSource = new BindingSource();
//...
cboIds.DataSource = bindingSource;
private void GetAvailableIds()
{
Task idTask = new Task(
() =>
{
bindingSource.Add("Searching..."); //This always updates the UI
//without invoking
if (cboIds.InvokeRequired)
{
Invoke((MethodInvoker)delegate
{ //This sometimes updates the UI without
cboIds.Enabled = false; //invoking, but sometimes fails, so I
}); //added the check
}
else
cboIds.Enabled = false;
List<string> temp = GetUpcomingIds();
Invoke((MethodInvoker)delegate
{
cboIds.Enabled = true;
bindingSource.Clear();
foreach (string str in temp)
bindingSource.Add(str); //This never works without invoking.
}); //Why, if the same operation above
}); //always works without invoking?
idTask.Start();
}
Why is it that the initial add to the BindingSource doesn't need an invoke, setting the combobox.enabled to false sometimes needs an invoke, and the final adds to the BindingSource always need to be invoked? If they are all on the same thread, shouldn't they behave the same? Am I wrong in my assumption that they are all on the same thread?