2013-05-01 88 views
1

我有一个具有各种元素的Canvas控件,在这个特定的函数中,我允许用户在画布周围拖动一条线的终点。在MouseMove函数中,我呼叫e.GetPosition()MouseMove性能使用GetPosition缓慢

根据VS性能分析器的测试结果,当应用程序不断移动时,该功能接近应用程序总CPU的30%。它非常缓慢。我能做些什么来提高这种表现?

CurrentPoint = e.GetPosition(PointsCanvas); 
+0

'在这个特定的功能,我允许用户拖动终点围绕画布“ - 我宁愿使用”Thumb“来处理'DragDelta'事件。 – 2013-05-01 16:24:36

+0

@HighCore你能解释一下你的意思吗?谢谢 – Chris 2013-05-02 07:54:18

回答

1

我一直在使用的MouseMove在Windows Phone所面临的同样的问题8.看来,拖动,事件(包含你所需要的坐标)以固定的时间间隔上调(取决于你做什么例如在听众的实现中,例如每20毫秒)。所以我做的是用我的坐标填充Queue,并创建一个线程,通过排队第一个元素并执行我想要的逻辑来消耗该队列。就像这个逻辑不是连续完成的,因为它是完成这项工作的另一个线程。 我不知道我是不是足够清楚,所以请看看下面的代码:

//Class used to store e.getPosition(UIElement).X/Y 
public class mouseInformation 
    { 
     public int x { get; set; } 
     public int y { get; set; } 


     public mouseInformation(int x, int y, String functionName) 
     { 
      this.x = x; 
      this.y = y;    
     } 
    } 



    private readonly Queue<mouseInformation> queueOfEvent = new Queue<mouseInformation>(); 

    //MouseMove listener 
    private void wpCanvas_MouseDragged(object sender, System.Windows.Input.MouseEventArgs e) 
    { 
     //Instead of "wpCanvas" put the name of your UIElement (here your canvas name) 
     mouseInformation mouseDragged = new mouseInformation((int)e.GetPosition(wpCanvas).X, (int)e.GetPosition(wpCanvas).Y); 

     EnqueueMouseEvent(mouseDragged); 

    } 

    //Allow you to add a MouseInformation object in your Queue 
    public void EnqueueMouseEvent(mouseInformation mi) 
    { 

     lock (queueOfEvent) 
     { 
      queueOfEvent.Enqueue(mi); 
      Monitor.PulseAll(queueOfEvent); 
     } 
    } 

    //Logic that your consumer thread will do 
    void Consume() 
    { 
     while (true) 
     { 
      mouseInformation MI; 

      lock (queueOfEvent) 
      {   
       while (queueOfEvent.Count == 0) Monitor.Wait(queueOfEvent); 
       MI = queueOfEvent.Dequeue(); 
      } 

       // DO YOUR LOGIC HERE 
       // i.e DoSomething(MI.x, MI.y)    
     } 
    } 

而且不要忘记创建您的主(线程),或在MainPage_Loaded(对象发件人, RoutedEventArgs e)方法,如果你是Windows手机用户。

System.Threading.ThreadStart WatchQueue = new System.Threading.ThreadStart(Consume); 
System.Threading.Thread RunWatchQueue = new System.Threading.Thread(WatchQueue); 
RunWatchQueue.Name = "Events thread"; 
RunWatchQueue.Start(); 

简单地说少,你在你的的MouseMove听众做,更快的速度将是。 您也可以异步执行该逻辑,或者甚至使用Bresenham algorithm来模拟更多事件。 希望它有帮助。

0

你是否在使用任何效果,如dropshaddow等? 我最近有这种情况,e.GetPosition()也使用了30%的应用程序的CPU资源,这没有任何意义吗? 我发现在视觉树上有一个控制应用drophaddow效果,这是什么东西放缓了这么多...