开发者

WPF threads - can't access property/field [duplicate]

开发者 https://www.devze.com 2023-04-13 02:56 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: The calling thread cannot access this object because a different thread owns it
This question already has answers here: Closed 11 years ago.

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()
{开发者_如何学Python
    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?


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();
    }));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号