0

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!

Jeff
  • 27
  • 7
  • Ignore BW for a minute, and take a step back. What is the **underlying business problem** you are trying to solve? – mjwills Oct 30 '17 at 10:05
  • I do data writing for another software (contains Thread.sleep()) and I need to display what kind of data writing I am doing in WPF UI during the process. – Jeff Oct 30 '17 at 10:08
  • Yes, it's suitable, but you need to either wrap your UI calls in Dispatcher.Invoke calls (the linked duplicate shows how to do this) or make any UI operations outside your BackgroundWorker's DoWork method. – Heinzi Oct 30 '17 at 10:08

0 Answers0