2

Ive got a wpf form, from which i want to display a loading popup as soon as the user makes a choice from the controls, because the loading of the data could take long seeing as the Database is not Local. I got everything working up until where i create the thread for the popup window.

This is where i create my Thread:

public void Start()
    {

         if (_parent != null)
             _parent.IsEnabled = false;

         _thread = new Thread(RunThread);

         _thread.IsBackground = true;
         _thread.SetApartmentState(ApartmentState.STA);
         _thread.Start();

         _threadStarted = true;
         SetProgressMaxValue(10);

         Thread th = new Thread(UpdateProgressBar);
         th.IsBackground = true;
         th.SetApartmentState(ApartmentState.STA);
         th.Start();
    }

And the thread Method:

private void RunThread()
    {

        _window = new WindowBusyPopup(IsCancellable);
        _window.Closed += new EventHandler(WaitingWindowClosed);
        _window.ShowDialog();
    }

Now the moment that executes i Get this error :

Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.

Any help would be appreciated :)

LU RD
  • 34,438
  • 5
  • 88
  • 296
user1168738
  • 21
  • 1
  • 2

2 Answers2

0

Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.

This error is observed because your are trying to use a resource(of the type UIElement) which was created in a different thread in your STA thread(which you are using to show the popup window).

In your case it looks like the second thread Thread th = new Thread(UpdateProgressBar); , is trying to manipulate the UI in the WindowBusyPopup. As the popup is owned by a different thread you are getting this exception.

Possible Solution: (as I see you dont show the implementation of the function UpdateProgressBar)

private void UpdateProgressBar()
{
if(_window != null) /* assuming  you declared your window in a scope accesible to this function */
_window.Dispatcher.BeginInvoke(new Action( () => {
// write any code to handle children of window here
}));
}
Karthik
  • 990
  • 10
  • 19
0

Try to use the Dispatcher property of the form. Dispatcher.BeginInvoke(...)

Or just use the BackgroundWorker class, because it has a method called ReportProgress() to report the progress percentage. This will fire the ProgressChanged event, when you can refresh the value of the progressbar or something...

laszlokiss88
  • 4,001
  • 3
  • 20
  • 26