开发者

Could this WPF code benefit from Parallel.For and how?

I'm wondering if there is a way to convert this so it would be more performant by using a Parallel.For for example.

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, FrameworkEl开发者_开发问答ement from)
{
    GeneralTransform transform = null;

    transform = of.TransformToVisual(from);

    return transform.TransformBounds(new Rect(0, 0, of.ActualWidth, of.ActualHeight));
}

Any suggestions?


I didn't actually test the following, so use at your own risk (-:
I'm assuming that reading ActualWidth/Height is thread-safe.

   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;
    }

And to answer the Title-question: You may see some speedup and with many nested elements it might be worth-while. This (tree-searching) is a rare case where you may see a better-than-linear improvement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜