I am trying to move some code which contains Thread.Sleep() into DoWork() function, otherwise the UI will be dead during Thread.Sleep(3000) - I need to display some messages during this period of time. But these code are triggered when there is change in combobox and based upon the content in the textblock and combobox of UI. When I run it, it reports that a different thread owns it. Here is my code:
bgWorker.DoWork += (obj, e) => WorkerDoWork(location, IsRunway);
private void WorkerDoWork(string location, bool IsRunway)
{
if (ListAirport.SelectedItem != null && ...) // reports exception - "a different thread owns it"
{
...
Thread.Sleep(3000);
}
}
private void ListRunway_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
set_button_default();
if(ListRunway.SelectedItem!=null)
{
if (bgWorker.IsBusy)
return;
else
this.Dispatcher.Invoke(() => bgWorker.RunWorkerAsync());
}
}
I think that it is because the code relevant to UI elements should not appear in DoWork() function. But I do need to move them to make the UI always alive. I appreciate any help!