Dispatcher.Invoke 和线程访问的问题
我尝试在 C# 中处理线程,但发生了一个奇怪的异常,我不知道如何解决。我有一个由BackgroundWorker运行的方法,其中有这样一段代码:
GridView gridView;
DataView dataView;
queryTable.GetViewAndDataView(out gridView, out dataView);
this.listView.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
delegate() {
listViewView = gridView;
listView.ItemsSource = dataView;
}
));
GetViewAndDataView填充gridView和dataView,而委托代码设置当前listView。使用 Invoke 应该不会引发异常,但是当我尝试运行它时,我得到了:调用线程无法访问此对象,因为另一个线程拥有它。
任何人都知道如何处理此类异常,或者至少知道如何禁用拥有的线程对象?
I've trying to handle threads in C#, but i've occurred in a wierd exception I don't know how to resolve. I've got a method running by BackgroundWorker, in which there's this piece of code:
GridView gridView;
DataView dataView;
queryTable.GetViewAndDataView(out gridView, out dataView);
this.listView.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
delegate() {
listViewView = gridView;
listView.ItemsSource = dataView;
}
));
GetViewAndDataView fills a gridView and dataView, while the delegate code sets the current listView. The using of Invoke is supposed not to raise exceptions, but when I try to run it, I obtain this: The calling thread cannot access this object because a different thread owns it.
Anyone knows of to handle such exception, or at least, how to disable the thread object owning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该消息是正确的,您无法在后台线程上创建控件并在 UI 线程上使用它们。您必须在 UI 线程上创建并分配它们。我建议首先在后台线程中加载数据,然后在 UI 线程中完成其余工作
The message is correct, you cant create the controls on a background thread and use them on your UI Thread. You have to both create and assign them on your UI thread. I recommend loading your data first in your background thread followed by doing the rest of your work in the UI Thread
在运行并行线程之前,您需要将
this.listView.Dispatcher
保存到某个局部变量。在 thred 中,您必须使用此变量中的调度程序。但是 @Polity 是对的 - 您必须创建控件UI 线程上的 /elements。在并行线程中,您只能创建非 UI 对象。
You need save
this.listView.Dispatcher
to some local variable before you run the parallel thread. In the thred you must use dispatcher from this variable.However @Polity is right - you must create controls/elements on UI thread. In parallel threads you can create only non-UI objects.