如何在UI线程中工作时更新进度条

时间:2015-06-18 01:49:34

标签: c# wpf treeview

我有一个ProgressBar和一个TreeView

我使用一堆数据填充了TreeView,一旦应用,我会遍历visual tree的{​​{1}},基本上强制它生成每个TreeView 。我希望TreeViewItems能够展示这是如何发展的。

这是我为创建ProgressBar而运行的行为代码。一旦TreeViewItems属性设置为true,它就开始处理项目。它反过来更新单例类中的属性以更新进度。

ItemsLoaded

Singleton Class

public class TreeViewBehaviors
{
    public static readonly DependencyProperty ItemsLoadedProperty =
        DependencyProperty.RegisterAttached("ItemsLoaded", typeof(bool), typeof(TreeViewBehaviors),
        new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnItemsLoadedPropertyChanged)));

    public static bool GetItemsLoaded(DependencyObject obj)
    {
        return (bool)obj.GetValue(ItemsLoadedProperty);
    }

    public static void SetItemsLoaded(DependencyObject obj, bool value)
    {
        obj.SetValue(ItemsLoadedProperty, value);
    }

    private static void OnItemsLoadedPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        if ((bool)e.NewValue)
        {
            GetTotalNTreeViewItems((TreeView)sender, sender);
        }
    }

    public static readonly DependencyProperty NodesProcessedProperty =
        DependencyProperty.RegisterAttached("NodesProcessed", typeof(int), typeof(TreeViewBehaviors),
        new FrameworkPropertyMetadata(default(int), new PropertyChangedCallback(OnNodesProcessedPropertyChanged)));

    public static int GetNodesProcessed(DependencyObject obj)
    {
        return (int)obj.GetValue(NodesProcessedProperty);
    }

    public static void SetNodesProcessed(DependencyObject obj, int value)
    {
        if (GetNodesProcessed(obj) != value)
        {
            obj.SetValue(NodesProcessedProperty, value);
        }
    }

    private static void OnNodesProcessedPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue != null)
        {
            double trouble = Math.Round(((GetProgressMaximum(sender) / GetTotalNodesToProcess(sender)) * (int)e.NewValue), 1);
            TreeViewSingletonClass.Instance.DisplayProgress = trouble;
        }
    }

    public static readonly DependencyProperty TotalNodesToProcessProperty =
        DependencyProperty.RegisterAttached("TotalNodesToProcess", typeof(double), typeof(TreeViewBehaviors),
        new FrameworkPropertyMetadata(default(double)));

    public static double GetTotalNodesToProcess(DependencyObject obj)
    {
        return (double)obj.GetValue(TotalNodesToProcessProperty);
    }

    public static void SetTotalNodesToProcess(DependencyObject obj, double value)
    {
        obj.SetValue(TotalNodesToProcessProperty, value);
    }


    public static readonly DependencyProperty ProgressMaximumProperty =
        DependencyProperty.RegisterAttached("ProgressMaximum", typeof(double), typeof(TreeViewBehaviors),
        new FrameworkPropertyMetadata(default(double)));

    public static double GetProgressMaximum(DependencyObject obj)
    {
        return (double)obj.GetValue(ProgressMaximumProperty);
    }

    public static void SetProgressMaximum(DependencyObject obj, double value)
    {
        obj.SetValue(ProgressMaximumProperty, value);
    }

    private static void GetTotalNTreeViewItems(ItemsControl container, DependencyObject sender)
    {
        if (container != null)
        {
            container.ApplyTemplate();
            ItemsPresenter itemsPresenter = (ItemsPresenter)container.Template.FindName("ItemsHost", container);
            if (itemsPresenter != null)
            {
                itemsPresenter.ApplyTemplate();
            }
            else
            {
                // The Tree template has not named the ItemsPresenter, 
                // so walk the descendents and find the child.
                itemsPresenter = FindVisualChild<ItemsPresenter>(container);
                if (itemsPresenter == null)
                {
                    container.UpdateLayout();
                    itemsPresenter = FindVisualChild<ItemsPresenter>(container);
                }
            }

            Panel itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0);

            // Ensure that the generator for this panel has been created.
            UIElementCollection children = itemsHostPanel.Children;
            for (int i = 0, count = container.Items.Count; i < count; i++)
            {
                TreeViewItem subContainer = (TreeViewItem)container.ItemContainerGenerator.ContainerFromIndex(i);
                GetTotalNTreeViewItems(subContainer, sender);
                SetNodesProcessed(sender, GetNodesProcessed(sender) + 1);
            }
        }
    }

    private static T FindVisualChild<T>(Visual visual) where T : Visual
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
        {
            Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
            if (child != null)
            {
                T correctlyTyped = child as T;
                if (correctlyTyped != null)
                    return correctlyTyped;

                T descendent = FindVisualChild<T>(child);
                if (descendent != null)
                    return descendent;
            }
        }
        return null;
    }
}

XAML:

public class TreeViewSingletonClass : INotifyPropertyChanged
{
    private static double m_DisplayProgress = 0;
    public double DisplayProgress
    {
        get { return m_DisplayProgress; }
        set
        {
            if (m_DisplayProgress == value)
                return;
            m_DisplayProgress = value;
            NotifyPropertyChanged();
        }
    }

    private static TreeViewSingletonClass m_Instance;
    public static TreeViewSingletonClass Instance
    {
        get
        {
            if (m_Instance == null)
                m_Instance = new TreeViewSingletonClass();
            return m_Instance;
        }
    }

    private TreeViewSingletonClass(){}

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

我的问题是,每件事情都在正确处理,只有<ProgressBar Grid.Column="2" Grid.Row="1" Margin="5" Width="20" Height="150" VerticalAlignment="Top" Value="{Binding Source={x:Static helpers:TreeViewSingletonClass.Instance}, Path=DisplayProgress}" Maximum="{Binding ProgressMaximum}" /> 直到最后才更新。我意识到这两个都在同一ProgressBar内联工作,所以这将成为问题。

所以我的问题是,如果这两个工作在同一个线程上,我怎么能让这个UI thread更新。

[编辑]

此WPF是ProgressBar UserControl中的WinForm,我只是将以下内容放入WinForm,以便我可以访问ElementHost

Application.Current

在尝试实现Xavier的第二个建议之后:将工作分成更小的部分,并使用BeginInvoke将调度程序单独排队(例如,将循环体转换为调度程序调用)

所以在if ( null == System.Windows.Application.Current ) { new System.Windows.Application(); } 循环中我坚持以下内容:

for

不幸的是,这没有用,必须做错事。

1 个答案:

答案 0 :(得分:2)

WPF中的UI线程使用Dispatcher来安排和处理UI的所有更新。调度程序基本上维护一个在线程上运行的任务队列。如果你垄断线程,队列将只备份,直到你给它一个再次运行的机会。

您的问题有多种可能的解决方案。这是一对......

在单独的线程上工作

我首先考虑的解决方案是将长期运行的任务转移到另一个线程而不是接管UI线程。您需要从该线程对UI进行的任何更新都可以通过使用BeginInvoke方法遍历UI线程的Dispatcher来完成。例如,如果我想在进度条的值中加1,我可能会这样做:

Dispatcher.BeginInvoke(new Action(delegate() { mProgress.Value += 1.0; }));

注意:确保您的工作线程有一种方法从UI线程引用调度程序。不要从工作线程调用Dispatcher.CurrentDispatcher,否则您将获得该线程的调度程序,而不能访问该UI。相反,您可以将调度程序传递给线程,或通过从UI线程设置的成员或属性访问它。

使用Dispatcher共享UI线程

如果您真的想要出于某种原因在UI线程上执行所有工作(如果您正在进行大量可视树行走或其他以UI为中心的任务,则可能会这样做),请考虑以下其中一项:

  • 将工作分成更小的部分,并使用BeginInvoke与调度员分别对齐这些部分。确保优先级足够低,以便UI更新不会等到最后。例如:

    for (int i = 0; i < 100; ++i)
    {
        Dispatcher.CurrentDispatcher.BeginInvoke(new Action(delegate()
        {
            mProgress.Value += 1.0;
            // Only sleeping to artificially simulate a long running operation
            Thread.Sleep(100);
        }), DispatcherPriority.Background);
    }
    
  • 在长时间运行期间根据需要处理调度程序队列。在&#34;备注&#34;中有一个为此目的创建DoEvents方法的示例。 PushFrame方法的文档部分。