190

Where can I find a control which is like the C# Timer Control in WPF?

4 Answers 4

351

The usual WPF timer is the DispatcherTimer, which is not a control but used in code. It basically works the same way like the WinForms timer:

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();


private void dispatcherTimer_Tick(object sender, EventArgs e)
{
  // code goes here
}

More on the DispatcherTimer can be found here

5
  • Hi, i've been trying to use dispatch timer but i cant find it in my intelisense is there any reference that needs to be added for me to use it?
    – yohannist
    Oct 15, 2012 at 22:26
  • 2
    I like the way you set the interval, better than milliseconds in my opinion.
    – JL.
    Aug 12, 2013 at 2:48
  • Be sure to call dispatcherTimer.Stop() when you close your form. The WinForms version of the timer does that automatically. (That's the advantage of making the timer a Control.) If you don't you'll have a memory leak and possibly other bugs. Nov 28, 2016 at 14:11
  • 8
    @JL Eh? That code is impossible to interpret. Far better is var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
    – Jim Balter
    Jun 20, 2017 at 5:11
  • In .NET 7.0 with VS 2022 I had to declare the timer function using nullable reference types like so. private void dispatcherTimer_Tick(object? sender, EventArgs? e) Jan 27 at 18:49
12

With Dispatcher you will need to include

using System.Windows.Threading;

Also note that if you right-click DispatcherTimer and click Resolve it should add the appropriate references.

3
  • need to add reference to WindowsBase.dll btw Jan 9, 2014 at 18:22
  • 19
    IMHO this doesn't answer the question about which control to use, it merely adds some commentary to the accepted answer. Jun 16, 2015 at 19:24
  • 4
    I added this in 2012, just really starting as a developer, I still get points for it. But as @StephenKennedy pointed out, this should be a comment.
    – Malcor
    May 3, 2016 at 14:28
3

you can also use

using System.Timers;
using System.Threading;
0
0

The timer has special functions.

  1. Call an asynchronous timer or synchronous timer.
  2. Change the time interval
  3. Ability to cancel and resume  

if you use StartAsync () or Start (), the thread does not block the user interface element

     namespace UITimer


     {
        using thread = System.Threading;
        public class Timer
        {

        public event Action<thread::SynchronizationContext> TaskAsyncTick;
        public event Action Tick;
        public event Action AsyncTick;
        public int Interval { get; set; } = 1;
        private bool canceled = false;
        private bool canceling = false;
        public async void Start()
        {
            while(true)
            {

                if (!canceled)
                {
                    if (!canceling)
                    {
                        await Task.Delay(Interval);
                        Tick.Invoke();
                    }
                }
                else
                {
                    canceled = false;
                    break;
                }
            }


        }
        public void Resume()
        {
            canceling = false;
        }
        public void Cancel()
        {
            canceling = true;
        }
        public async void StartAsyncTask(thread::SynchronizationContext 
        context)
        {

                while (true)
                {
                    if (!canceled)
                    {
                    if (!canceling)
                    {
                        await Task.Delay(Interval).ConfigureAwait(false);

                        TaskAsyncTick.Invoke(context);
                    }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }

        }
        public void StartAsync()
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while (true)
                {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);

                    Application.Current.Dispatcher.Invoke(AsyncTick);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }

        public void StartAsync(thread::SynchronizationContext context)
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while(true)
                 {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);
                            context.Post((xfail) => { AsyncTick.Invoke(); }, null);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }
        public void Abort()
        {
            canceled = true;
        }
    }


     }
1
  • 1
    Can you explain your code? If you just post some code, people won't learn from it and just copy & paste some code from the web.
    – Robert
    Dec 27, 2019 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.