【问题标题】:WPF threads - can't access property/field [duplicate]WPF线程-无法访问属性/字段[重复]
【发布时间】:2011-12-08 16:08:38
【问题描述】:

可能重复:
The calling thread cannot access this object because a different thread owns it

我正在我的应用程序中编写一些线程处理:

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

调用的方法是这个:

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

在“客户端”中我是这样使用的:

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

TableListView里面有一个方法:

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

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

iItems 定义为:

private List<TablesListViewItem> items;

在一行

ListItemContainer.Children.Add(item);

我收到 InvalidOperationException 异常并显示消息:调用线程无法访问此对象,因为不同的线程拥有它。

整个代码都用于 WPF。我试图切换到属性,但没有效果。我以为 Dispatcher 会完成这项工作……我做错了什么?

【问题讨论】:

  • 您真的需要 STA 吗?
  • 没有它,应用程序崩溃,并显示只有 STA 可以访问 UI 控件(或类似的东西)的消息
  • 尝试像这样获取调度程序 - Application.Current.Dispatcher

标签: .net wpf multithreading properties


【解决方案1】:

更改以下行

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

private void Refresh()
{
    Application.Current.Dispatcher.Invoke(new Action(()=>
    {
      ViewDataCollection.GetData<TableViewData>().Tables = GameClient.ListTables();
      tablesListView1.SetItems(ViewDataCollection.GetData<TableViewData>().Tables);
      tablesListView1.Refresh();
    }));
}

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2018-05-15
    • 2013-03-20
    • 2011-11-05
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多