&引用;调用线程无法访问此对象,因为其他线程拥有它";C#WPF应用程序中出现错误?
我正在做一个下载程序。在我的项目中有名为main.xaml.cs和downloader.cs的主窗口和下载程序类 主窗口中有一个自定义列表框。我试图从Downloader.cs刷新Listbox项,但应用程序给出了“调用线程无法访问此对象,因为另一个线程拥有”错误 Downloader.cs:&引用;调用线程无法访问此对象,因为其他线程拥有它";C#WPF应用程序中出现错误?,c#,.net,wpf,xaml,listbox,C#,.net,Wpf,Xaml,Listbox,我正在做一个下载程序。在我的项目中有名为main.xaml.cs和downloader.cs的主窗口和下载程序类 主窗口中有一个自定义列表框。我试图从Downloader.cs刷新Listbox项,但应用程序给出了“调用线程无法访问此对象,因为另一个线程拥有”错误 Downloader.cs: namespace MyDownloaderApp { class Downloader { /* ... */ priv
namespace MyDownloaderApp
{
class Downloader
{
/*
...
*/
private void doWork()
{
((MainWindow)System.Windows.Application.Current.MainWindow).myListBox.Items.Refresh();
}
}
}
An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code: "The calling thread cannot access this object because a different thread owns it."
我收到以下错误:
namespace MyDownloaderApp
{
class Downloader
{
/*
...
*/
private void doWork()
{
((MainWindow)System.Windows.Application.Current.MainWindow).myListBox.Items.Refresh();
}
}
}
An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code: "The calling thread cannot access this object because a different thread owns it."
导致此错误的原因以及我如何修复它?您应该使用:
this.Dispatcher.Invoke((Action)(() =>
{
...// your code refresh listbox Items
}));
请查看:正确的方法是使用绑定,而不是直接操作列表框。而且会很有用。我已经在使用绑定了。我想在向列表框添加数据后刷新列表框项目。然后,使用
ObservableCollection
和BindingOperations.EnableCollectionSynchronization
,它会自动更新。您可以使用this.Dispatcher.BeginInvoke
而不是this.Dispatcher.Invoke
。