-2

In my project I have a busyindicator and I'm using ListObject in FirstMethod and SecondMethod.

The program gives the following error:

The calling thread cannot access the object because a different thread owns it

I am using the following code:

public static readonly DependencyProperty ListObjectProperty = 
    DependencyProperty.Register("ListObject", typeof(ObservableCollection<FileViewModel>), typeof(MyObjectViewModel), new PropertyMetadata(ChangeCallback));

public ObservableCollection<FileViewModel> ListObject
{
    get { return (ObservableCollection<FileViewModel>)GetValue(ListObjectProperty); }
    set { SetValue(ListObjectProperty, value); }
}

private void SelectedPath()
{
    NavigatePage(new Page2());              
    FirstMethod();
}


private void FilesCase()
{
    var t = new Task(() => this.ThreadFilesCase());

    t.ContinueWith(
        (o) =>
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                IsBusy = false; NavigatePage(new Page3());
            }));
        });

    IsBusy = true;    
    t.Start();
}

private void ThreadFilesCase()
{
       SecondMethod();      
}   
KodeKreachor
  • 8,852
  • 10
  • 47
  • 64
zrab
  • 60
  • 9
  • Have you checked this? http://stackoverflow.com/questions/10764747/exception-the-calling-thread-cannot-access-this-object-because-a-different-thr You'll likely need to set up a delegate and invoke. – Corey Jan 30 '13 at 19:56
  • Is there anything in `SecondMethod` that is accessing a `UIElement` – sa_ddam213 Jan 30 '13 at 20:05
  • This is most likely due multithreading. I answered anyway, helping you with your specific problem. Try reading some stuff on multi threading and updating ui controls from another thread. – Jordy Langen Jan 30 '13 at 20:08
  • "… You'll likely need to set up a delegate and invoke" - can you write any example – zrab Jan 30 '13 at 20:08

1 Answers1

1

You are calling Dispatcher.BeginInvoke, withtin the ContinueWith delegate. Meaning it's invoking on the backgroundworker thread. Use the Dispatcher obtained from the ui control. Or use the SynchronizationContext that is used when the ui controls are (being) created.

Example: myBusyIndicator.Dispatcher.Invoke(...), instead off Dispatcher.Invoke(...)

Jordy Langen
  • 3,591
  • 4
  • 23
  • 32