C# WPF 应用程序中"The calling thread cannot access this object because a different thread owns it"错误?



我正在制作一个下载应用程序。在我的项目中有名为main.xaml.cs和downloader.cs的主窗口和下载程序类。

主窗口中有一个自定义ListBox。我正试图刷新Downloader.cs中的Listbox项,但应用程序给出了"调用线程无法访问此对象,因为另一个线程拥有";错误

下载程序.cs:

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

请查看:调用线程无法访问此对象,因为另一个线程拥有它

相关内容

最新更新