【问题标题】:Worker Thread was not updating the visibility status of the button工作线程未更新按钮的可见性状态
【发布时间】:2013-03-11 14:46:01
【问题描述】:

我在 wpf 应用程序中借助 BackgroundWorker 进行批量复制操作。我从工作线程调用方法 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 线程状态?

【问题讨论】:

    标签: c# wpf c#-4.0 wpf-controls


    【解决方案1】:

    只有在 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;
        });
      }
    }
    

    【讨论】:

    • 没关系。工作进程大约需要 5 或 6 分钟才能完成。那么如何在 UI 线程的帮助下找出完成并更新状态呢?
    • @RameshMuthiah:使用 BackgroundWorker 好友或任何线程级事件
    • 谢谢。它帮助了我
    【解决方案2】:

    如果您从不同的线程访问,请编组控制访问。在 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;
                                         };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 2013-05-08
      • 2020-08-03
      • 2011-04-04
      相关资源
      最近更新 更多