C# 工作线程未更新按钮的可见性状态

C# 工作线程未更新按钮的可见性状态,c#,wpf,c#-4.0,wpf-controls,C#,Wpf,C# 4.0,Wpf Controls,我已经在wpf应用程序中的BackgroundWorker的帮助下完成了批量复制操作。我从worker线程调用方法DoAction,如下所示 private void DoAction() { ..................... ..................... // some code goes here and works fine //Enable the Explore link to verify the package

我已经在wpf应用程序中的BackgroundWorker的帮助下完成了批量复制操作。我从worker线程调用方法DoAction,如下所示

private void DoAction()
  {

     .....................
     .....................   // some code goes here and works fine

     //Enable the Explore link to verify the package
     BuildExplorer.Visibility = Visibility.Visible; // here enable the button to visible and gives error
  }

如果我在最后看到BuildExplorer按钮可见性,它会说错误“调用线程无法访问此对象,因为其他线程拥有它。”我如何更新UI线程状态?

在WPF中从UI线程修改UI是唯一合法的。更改可见性等操作正在修改UI,不能从后台工作人员执行。您需要从UI线程执行此操作

在WPF中最常用的方法是

  • 在UI线程中捕获
    Dispatcher.CurrentDispatcher
  • 对从后台线程捕获的值调用
    Invoke
    ,对UI线程执行操作
比如说

class TheControl { 
  Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;

  private void DoAction() {
    _dispatcher.Invoke(() => { 
      //Enable the Explore link to verify the package
      BuildExplorer.Visibility = Visibility.Visible;
    });
  }
}

如果从不同线程访问,请封送控件访问。在Windows和许多其他操作系统中,控件只能由其所在的线程访问。你不能用另一根线来摆弄它。在WPF中,调度程序需要与UI线程关联,并且您只能通过调度程序封送调用

如果任务运行时间较长,则使用BackgroundWorker类获取完成通知

var bc = new BackgroundWorker();
    // showing only completed event handling , you need to handle other events also
        bc.RunWorkerCompleted += delegate
                                     {
                                        _dispatcher.Invoke(() => { 
                                        //Enable the Explore link to verify the package
                                        BuildExplorer.Visibility = Visibility.Visible;
                                     };

没关系。工人流程大约需要5或6分钟才能完成。那么我怎样才能在UI线程的帮助下发现完成情况并更新状态?@RameshMuthiah:使用BackgroundWorker buddy或任何线程级别的事件谢谢。它帮助了我