1

Possible Duplicate:
The calling thread cannot access this object because a different thread owns it

I'm writing some thread handling in my app:

BackgroundWorkers()
{
    WorkerThread = new Thread(new ThreadStart(Loop));
    WorkerThread.SetApartmentState(ApartmentState.STA);
    WorkerThread.Start();
}

The called method is this one:

    public static void Loop()
    {
        while (true)
        {
            if (BackgroundWorkersTick != null)
            {
                BackgroundWorkersTick();
            }
            Thread.Sleep(30 * 1000);
        }
    }

in the "client" I use it this way:

BackgroundWorkers.BackgroundWorkersTick += new BackgroundWorkers.BackgroundWorkersTickHandler(Refresh);
...
private void Refresh()
{
    ViewDataCollection.GetData<TableViewData>().Tables = GameClient.ListTables();
    tablesListView1.SetItems(ViewDataCollection.GetData<TableViewData>().Tables);
    tablesListView1.Refresh();
}

TableListView inside has a method:

    public void Refresh() { ListItemContainer.Dispatcher.Invoke((Action)BindItems); }

    private void BindItems()
    {
        ListItemContainer.Children.Clear();
        foreach (TablesListViewItem item in items)
        {
            ListItemContainer.Children.Add(item);
        }
    }

iItems is defined as:

private List<TablesListViewItem> items;

In the line

ListItemContainer.Children.Add(item);

I'm getting exception of InvalidOperationException with message: The calling thread cannot access this object because a different thread owns it.

This whole code goes for WPF. I tried to switch to property, but no effect. I thought that the Dispatcher will do the work... What I'm doing wrong?

Community
  • 1
  • 1
deha
  • 805
  • 8
  • 29

1 Answers1

2

Change the following lines

private void Refresh()
{
    ViewDataCollection.GetData<TableViewData>().Tables = GameClient.ListTables();
    tablesListView1.SetItems(ViewDataCollection.GetData<TableViewData>().Tables);
    tablesListView1.Refresh();
}

To

private void Refresh()
{
    Application.Current.Dispatcher.Invoke(new Action(()=>
    {
      ViewDataCollection.GetData<TableViewData>().Tables = GameClient.ListTables();
      tablesListView1.SetItems(ViewDataCollection.GetData<TableViewData>().Tables);
      tablesListView1.Refresh();
    }));
}
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131