Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在UI线程中工作时更新进度条_C#_Wpf_Treeview - Fatal编程技术网

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

C# 如何在UI线程中工作时更新进度条,c#,wpf,treeview,C#,Wpf,Treeview,我有一个ProgressBar和一个TreeView 我用一堆数据填充了TreeView,一旦应用了它,我就会运行TreeView的visual tree,基本上强制它生成每个TreeView项。我想让ProgressBar显示这是如何进展的 这是我运行以创建TreeViewItems的行为代码。一旦ItemsLoaded属性设置为true,它就会开始处理项目。它反过来更新singleton类中的属性以更新进度 public class TreeViewBehaviors { publi

我有一个
ProgressBar
和一个
TreeView

我用一堆数据填充了
TreeView
,一旦应用了它,我就会运行
TreeView
visual tree
,基本上强制它生成每个
TreeView项。我想让
ProgressBar
显示这是如何进展的

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

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:

<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}"  />
在尝试实现Xavier的第二个建议后:将工作分成更小的部分,并使用BeginInvoke与调度程序单独排队(例如,将循环体转换为调度程序调用)

因此,在
for
循环中,我坚持了以下几点:

for (int i = 0, count = container.Items.Count; i < count; i++)
{
    Application.Current.Dispatcher.BeginInvoke(new Action(delegate()
    {
        TreeViewItem subContainer = (TreeViewItem)container.ItemContainerGenerator.ContainerFromIndex(i);
        GetTotalNTreeViewItems(subContainer, sender);
        SetNodesProcessed(sender, GetNodesProcessed(sender) + 1); 
    }));
}
for(int i=0,count=container.Items.count;i

不幸的是,这没有起作用,一定是做错了什么。

WPF中的UI线程使用调度和处理UI的所有更新。dispatcher基本上维护一个要在线程上运行的任务队列。如果您独占线程,队列将立即备份,直到您给它一个再次运行的机会

您的问题有多种可能的解决方案。这里有几个

在单独的线程上工作

我可能首先考虑的是将你的长时间运行的任务移到另一个线程,而不是接管UI线程。您需要从该线程对UI进行的任何更新都可以通过使用该方法通过UI线程的Dispatcher来完成。例如,如果我想向进度条的值添加1,我可能会执行以下操作:

Dispatcher.BeginInvoke(new Action(delegate() { mProgress.Value += 1.0; }));
注意:确保您的工作线程能够从UI线程引用dispatcher。不要从工作线程调用
Dispatcher.CurrentDispatcher
,否则您将获得该线程的Dispatcher,该线程无法访问UI。相反,您可以将dispatcher传递给线程,或者通过从UI线程设置的成员或属性访问它

使用Dispatcher共享UI线程

如果你真的想用一个或另一个原因来执行UI线程上的所有工作(如果你正在做很多视觉树行走或其他UI任务),请考虑下列之一:

for (int i = 0, count = container.Items.Count; i < count; i++)
{
    Application.Current.Dispatcher.BeginInvoke(new Action(delegate()
    {
        TreeViewItem subContainer = (TreeViewItem)container.ItemContainerGenerator.ContainerFromIndex(i);
        GetTotalNTreeViewItems(subContainer, sender);
        SetNodesProcessed(sender, GetNodesProcessed(sender) + 1); 
    }));
}
  • 将工作分成更小的部分,并使用调度程序将这些部分单独排队。确保优先级足够低,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);
    }
    
    for(int i=0;i<100;++i)
    {
    Dispatcher.CurrentDispatcher.BeginInvoke(新操作(委托)()
    {
    M进程值+=1.0;
    //只有睡觉才能人工模拟长时间运行的操作
    睡眠(100);
    }),DispatcherPriority.Background);
    }
    
  • 在长时间运行操作期间,根据需要处理调度程序队列。为此,在方法文档的“备注”部分有一个创建
    DoEvents
    方法的示例


因此,如果我使用“将工作分成小块并排队”,我可能需要一些帮助。你能给我举个例子吗?我还忘了提到这个WPF是WinForm ElementHost中的一个用户控件,这有什么区别吗?我在回答中添加了一个例子。您不应该需要
应用程序
实例来访问dispatcher。只需导入
System.Windows.Threading
命名空间并使用
Dispatcher.CurrentDispatcher
。我第一次忘记提到的一件事是,您需要指定足够低的
DispatcherPriority
,以确保任何UI更新不会在等待所有操作完成时停滞<代码>调度优先级。背景通常是好的。我不知道控件位于WinForms ElementHost内部是否会产生影响。这不是我曾经尝试处理的事情。似乎没有什么不同,很好地工作。谢谢你的解决方案!
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);
}