Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to handle event only if some time passed after last firing?

Tags:

c#

.net

c#-4.0

I have event handler:

 private void Control_Scroll(object sender, ScrollEventArgs e)
 {
     UpdateAnnotations();
 }     

Now I wish to update annotations only if user stopped scrolling, like if since last scrolling event passed 100ms, then execute action, else discard it, as it won't matter anyway.

What would be the easiest/reusable way to do that, preferably some static method like public static void DelayedAction(Action action, TimeSpan delay).

Using .NET 4.0.

like image 553
Giedrius Avatar asked Nov 29 '25 16:11

Giedrius


2 Answers

See this answer to an Rx (Reactive Extensions) question. (You can use Observable.FromEvent to create an observable from an event.)

like image 117
Paul Ruane Avatar answered Dec 02 '25 07:12

Paul Ruane


I would go with something like this

class MyClass
{
   private System.Timers.Timer _ScrollTimer;
   public MyClass()
   {
       _ScrollTimer= new System.Timers.Timer(100);
       _ScrollTimer.Elapsed += new ElapsedEventHandler(ScrollTimerElapsed);
   }

   private void ResetTimer()
   {
        _ScrollTimer.Stop();
        _ScrollTimer.Start();
   }

   private void Control_Scroll(object sender, ScrollEventArgs e, TimeSpan delay)
    {
        ResetTimer();
    }    

    private void ScrollTimerElapsed(object sender, ElapsedEventArgs e)
    {
        _ScrollTimer.Stop();
        UpdateAnnotations();           
    }
}

Every time the user scrolls, the timer gets reset and only when scrolling stops for 100ms the TimerElapsed gets fired and you can update your annotations.

like image 41
Zaid Amir Avatar answered Dec 02 '25 06:12

Zaid Amir