Where can I find a control which is like the C# Timer Control in WPF?
4 Answers
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
5With 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.
3you can also use
using System.Timers;
using System.Threading; 0 The timer has special functions.
- Call an asynchronous timer or synchronous timer.
- Change the time interval
- 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