在哪里可以找到一个类似于 WPF 中的 C # 定时器控件的控件?
通常的 WPF 定时器是 DispatcherTimer,它不是一个控件,但在代码中使用。它的工作方式与 WinForms 计时器基本相同:
DispatcherTimer
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 }
关于 DispatcherTimer 的更多信息可以找到 给你
在 Dispatcher 中,您需要包括
using System.Windows.Threading;
还要注意,如果右键单击 DispatcherTimer 并单击 Resolve,则应添加适当的引用。
你也可以使用
using System.Timers; using System.Threading;
计时器有特殊的功能。
如果使用 StartAsync ()或 Start (),则线程不会阻塞用户界面元素
StartAsync ()
Start ()
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; } } }