【问题标题】:The calling thread cannot access the object because a different thread owns it调用线程无法访问该对象,因为不同的线程拥有它
【发布时间】:2013-01-14 18:24:27
【问题描述】:

在我的项目中,我有一个busyindicator,我在FirstMethodSecondMethod 中使用ListObject

程序给出以下错误:

调用线程无法访问该对象,因为不同的线程拥有它

我正在使用以下代码:

public static readonly DependencyProperty ListObjectProperty = 
    DependencyProperty.Register("ListObject", typeof(ObservableCollection<FileViewModel>), typeof(MyObjectViewModel), new PropertyMetadata(ChangeCallback));

public ObservableCollection<FileViewModel> ListObject
{
    get { return (ObservableCollection<FileViewModel>)GetValue(ListObjectProperty); }
    set { SetValue(ListObjectProperty, value); }
}

private void SelectedPath()
{
    NavigatePage(new Page2());              
    FirstMethod();
}


private void FilesCase()
{
    var t = new Task(() => this.ThreadFilesCase());

    t.ContinueWith(
        (o) =>
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                IsBusy = false; NavigatePage(new Page3());
            }));
        });

    IsBusy = true;    
    t.Start();
}

private void ThreadFilesCase()
{
       SecondMethod();      
}   

【问题讨论】:

  • 你检查过这个吗? stackoverflow.com/questions/10764747/… 您可能需要设置一个委托并调用。
  • SecondMethod 中是否有任何东西正在访问UIElement
  • 这很可能是由于多线程。我还是回答了,帮助你解决你的具体问题。尝试阅读一些关于多线程和从另一个线程更新 ui 控件的内容。
  • "...你可能需要设置一个委托并调用" - 你能写任何例子吗

标签: c# wpf busyindicator


【解决方案1】:

您正在调用Dispatcher.BeginInvoke,在ContinueWith 委托内。这意味着它正在后台工作线程上调用。使用从 ui 控件获得的 Dispatcher。或者使用在(正在)创建 ui 控件时使用的SynchronizationContext

例如:myBusyIndicator.Dispatcher.Invoke(...),而不是关闭Dispatcher.Invoke(...)

【讨论】:

  • 我没有在我的 xaml 中使用 myBusyIndi​​cator -
  • 然后给你的指标一个名字,这样你就可以在后面的代码中访问它
  • 它是导航页面项目,每个页面都有自己的viewModel。我无法解析 MyViewModel 中的指标名称
猜你喜欢
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多