As you've discovered, you cannot access UI controls from a non-UI thread. Which is why the first thing your
CreateResultsListItem
does is check whether it's running on a non-UI thread, and if so, invoke the method on the UI thread instead.
But that means your code does the following:
- On the UI thread,
startButton_Click
starts a new thread to call the CreateResultsListItem
method; CreateResultsListItem
finds that it's not running on the UI thread, and marshals the call back to the UI thread;CreateResultsListItem
then runs a second time on the UI thread, blocking the UI until it has finished;- The first call to
CreateResultsListItem
running on the background thread is notified that the second call has completed, and the new thread ends.
Hopefully you can see from that description that there is
absolutely no benefit in starting a new thread to call
CreateResultsListItem
. In fact, it's actually a dangerous thing to do - if you decided to wait for the background thread to finish, you'd end up with a deadlock, and your application would hang indefinitely.
Just call the
CreateResultsListItem
method directly from the UI thread:
private void startButton_Click(object sender, EventArgs e)
{
resultsList.Items.Clear();
if (Searcher.Start(pars) == true)
{
DisableButtons();
CreateResultsListItem();
}
}