1

我有一个来自 wpf 扩展工具包的 BusyIndi​​cator,我正在运行一个需要一段时间才能完成的函数。如果我在单独的线程中运行耗时的任务,我会收到 NotSupportedException,因为我正在尝试将对象从那个不同的线程插入到 ObservableCollection 中。如果可能的话,我真的不想花很多时间重构代码......有没有办法可以在单独的线程中设置指示器的可见性?

编辑

ThreadStart start = delegate()
  {
      System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
          {
              IsBusy = true;
          }));
   };

new Thread(start).Start();                                
longRunningFunction();

这对我也不起作用。

4

2 回答 2

1

你应该能够使用Dispatcher类似的东西。例如

Application.Current.Dispatcher.Invoke((Action)(() =>
{
    _indicator.Visibility = Visibility.Visible;
}));

这将导致代码在 UI 线程上运行。

在threading model reference中有更多信息(包括如何“正确”执行此操作,CheckAccess等等)。

于 2011-08-31T20:54:31.477 回答
0

您无法从后台工作人员访问 UI 控件。您通常所做的是在调用 BackgroundWorker.RunWorkerAync() 之前将 IsBusy 设置为 true,然后在 BackgroundWorker.RunWorkerCompleted 事件处理程序中将 IsBusy 设置为 false。类似于:

Backgroundworker worker = new BackgroundWorker();
worker.DoWork += ...
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
     IsBusy = false;
};
IsBusy = true;
worker.RunWorkerAsync();

您可以在 DoWork 事件处理程序中使用 Dispatcher 将项目添加到 ObservableCollection。

编辑:这是完整的解决方案

        private void Button_Click(object sender, RoutedEventArgs e)
    {
        //on UI thread
        ObservableCollection<string> collection;

        ThreadStart start = delegate()
        {
            List<string> items = new List<string>();
            for (int i = 0; i < 5000000; i++)
            {
                items.Add(String.Format("Item {0}", i));
            }

            System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                //propogate items to UI
                collection = new ObservableCollection<string>(items);
                //hide indicator
                _indicator.IsBusy = false;
            }));
        };
        //show indicator before calling start
        _indicator.IsBusy = true;
        new Thread(start).Start();      
    }
于 2011-08-31T20:57:37.210 回答