DispatcherTimer 不能保证会正好在时间间隔发生时执行计时器,但能够保证不会在时间间隔发生之前执行计时器。 这是因为 DispatcherTimer 操作与其他操作一样被放置到 何时执行 DispatcherTimer 操作取决于队列中的其他作业及其优先级
如果希望尽可能精确,请尽量使用System.Thread.Timer,从缓冲池里分配线程,进行作业。
public static int flag = 0;
private DateTime last;
private System.Threading.Timer threadingTimer;
public MainWindow()
{
threadingTimer = new System.Threading.Timer(new System.Threading.TimerCallback(ThreadMethod), null, -1, 1000);
}
delegate void SetTextCallback(string text);
public void SetText(string text)
{
//textBox1.Text+=text;
}
private void ThreadMethod(object state)
{
flag++;
string text = "+" + (DateTime.Now - last).TotalMilliseconds.ToString() + " ms. " +
"TimerThreadID: " + Thread.CurrentThread.ManagedThreadId.ToString() + ". Flag: " + flag + "\r\n";
last = DateTime.Now;
SetTextCallback d = new SetTextCallback(SetText);
this.Dispatcher.Invoke(d, new object[] { text });
}