代码之家  ›  专栏  ›  技术社区  ›  TimothyP

这个wpf代码能从parallel中获益吗?为什么?

  •  2
  • TimothyP  · 技术社区  · 14 年前

    我想知道是否有办法把这个转换成更高效的 例如,用一个平行线。

    public FrameworkElement FindIntersectingElement(Rect rectangle, UIElement activeElement)
    {    
        foreach (var child in this.Children)
        {
            if (child != activeElement)
            {
                if (GetBounds(child as FrameworkElement, this).IntersectsWith(rectangle))
                {
                    return child as FrameworkElement;
                }
            }
        }
    
        return null;
    }
    
    public Rect GetBounds(FrameworkElement of, FrameworkElement from)
    {
        GeneralTransform transform = null;
    
        transform = of.TransformToVisual(from);
    
        return transform.TransformBounds(new Rect(0, 0, of.ActualWidth, of.ActualHeight));
    }
    

    有什么建议吗?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Henk Holterman    14 年前

    我并没有实际测试以下内容,所以请自行承担使用风险。
    我假设读取实际宽度/高度是线程安全的。

       public FrameworkElement FindIntersectingElement(Rect rectangle, UIElement activeElement)
        {
            FrameworkElement found = null;
    
            System.Threading.Tasks.Parallel.ForEach((IEnumerable<UIElement>)MainPanel.Children, 
               (child, loopState) =>
            {
                if (child != activeElement)
                {
                    if (GetBounds(child as FrameworkElement, MainPanel).IntersectsWith(rectangle))
                    {
                        found = child as FrameworkElement;
                        loopState.Stop();
                    }
                }
            });
            return found;
        }
    

    要回答标题问题:您可能会看到一些加速和许多嵌套元素,这可能是值得的。这(树搜索)是一个罕见的情况下,你可能会看到比线性改善更好。