-1

I'm making a downloader application. There are main window and downloader classes named Main.xaml.cs and Downloader.cs in my project.

There is a custom ListBox in the main window. I'm trying to refresh the Listbox item from the Downloader.cs, but the application gives the "The calling thread cannot access this object because a different thread owns" error.

Downloader.cs:

namespace MyDownloaderApp
{
    class Downloader
    {
        /*
        ...
        */

        private void doWork()
        {
            ((MainWindow)System.Windows.Application.Current.MainWindow).myListBox.Items.Refresh();
        }
    }
}

I got the following error:

An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code: "The calling thread cannot access this object because a different thread owns it."

What is causing this error and how can I fix it?

Firat Eski
  • 661
  • 2
  • 7
  • 16
  • The proper way to do this is to use bindings rather than to manipulate the listbox directly. And [this](https://msdn.microsoft.com/en-us/library/hh140164.aspx) will be useful. – Lucas Trzesniewski Dec 06 '15 at 15:52
  • I'm already using binding. I want to refresh the listbox items after the adding data to listbox. – Firat Eski Dec 06 '15 at 15:57
  • 1
    Well, then use an `ObservableCollection` along with `BindingOperations.EnableCollectionSynchronization` and it will update itself. – Lucas Trzesniewski Dec 06 '15 at 16:14

1 Answers1

2

You should use :

this.Dispatcher.Invoke((Action)(() =>
    {
        ...// your code refresh listbox Items
    }));

please have a look at : The calling thread cannot access this object because a different thread owns it

Community
  • 1
  • 1
Luke Le
  • 728
  • 1
  • 9
  • 24