WPF 线程 - 无法访问属性/字段
可能的重复:
调用线程无法访问此对象对象,因为不同的线程拥有它
我正在我的应用程序中编写一些线程处理:
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。我尝试切换到属性,但没有效果。我以为调度员会完成这项工作...我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将以下行更改
为
Change the following lines
To