M_K
M_K

Reputation: 3455

How can I make a timer last for a minute then stop

I am using a DispatchTimer to do something every second, how can I make it do Something for a set amount of time say 1 minute or 2 minutes? Do I need anther nested DispatcherTimer?

My code is below

System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();

    private void StartButton_Click(object sender, RoutedEventArgs e)
    {
        TimeSpan interval;
        interval = (TimeSpan)intervalPicker.Value;
        dt.Interval = interval;
        dt.Tick += new EventHandler(dt_Tick);
        dt.Start();
    }

    void dt_Tick(object sender, EventArgs e)
    {
       //Do Something
    }

I would appreciate if you could help me thanks.

Upvotes: 2

Views: 1436

Answers (2)

thumbmunkeys
thumbmunkeys

Reputation: 20764

Use the Stopwatch class:

Stopwatch sw = new Stopwatch();

private void StartButton_Click(object sender, RoutedEventArgs e)
{
    sw.Start();
    ...
}

void dt_Tick(object sender, EventArgs e)
{
   // stops the timer after 66 seconds
   if(sw.ElapsedMilliseconds/1000 > 66)
   {
       dt.Stop();
       sw.Reset();
   }          
}

Upvotes: 5

Pedro Lamas
Pedro Lamas

Reputation: 7233

Cimbalino Windows Phone Toolkit (available in NuGet) contains a DispatcherExtensions class with a BeginInvokeAfterTimeout() method that executes an Action after the specified timeout.

If you prefer, you can just copy the DispatcherExtensions file from the source code and use it in your own project.

Upvotes: 1

Related Questions