Câu trả lời:
Bộ định thời WPF thông thường là DispatcherTimer, không phải là điều khiển mà được sử dụng trong mã. Về cơ bản, nó hoạt động giống như bộ đếm thời gian WinForms:
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
}
Thông tin thêm về DispatcherTimer có thể được tìm thấy ở đây
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
Với Dispatcher, bạn sẽ cần bao gồm
using System.Windows.Threading;
Cũng lưu ý rằng nếu bạn nhấp chuột phải vào DispatcherTimer và nhấp vào Giải quyết thì nên thêm các tham chiếu thích hợp.
bạn cũng có thể dùng
using System.Timers;
using System.Threading;
Bộ hẹn giờ có các chức năng đặc biệt.
nếu bạn dùng StartAsync () hoặc Start (), luồng không chặn thành phần giao diện người dùng
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;
}
}
}