我有这个计时器的问题,我在 Tick 事件中的函数出现了两次..我希望它只出现一次.. public void timerStart() { DispatcherTimer updaterTimer = new DispatcherTimer(); updaterTimer.Tick += new EventHandler(updaterTimer_Tick); updaterTimer.Interval = new TimeSpan(0,0,0,0,300); updaterTimer.Start(); } private void updaterTimer_Tick(object sender, EventArgs e) { updaterTimer.Stop(); checkSigningAvailable(); updaterTimer.Start(); }这是在计时器的每个滴答声中检查的方法, public void checkSigningAvailable() { if (dt_signing_in.CompareTo(DateTime.Now) < 0) { if (!InPopAlready) { InPopAlready = true; disableSigningIn("False", this.event_id); } } }调用上面的这个函数后,底部的消息框出现了两次 public void disableSigningIn(string Out,string event_id) { System.Console.WriteLine("POPED "+ InPopAlready); connection.Open(); string sign = "True," + Out; string query = "update data_storage set data_details = '" + sign + "' where data_name = 'Signing';"; NpgsqlCommand command = new NpgsqlCommand(query, connection); command.ExecuteNonQuery(); connection.Close(); sign_in.Content = "Sign-in Time : Over"; string query2 = concatQuery(getIDnumberAttendance(event_id)); updateAbsences(query2); MessageBox.Show("Signing in is over!", "No more signing in!", MessageBoxButton.OK, MessageBoxImage.Information);} 最佳答案 您正在添加“+= new EventHandler ”并在新的 EventHandlers 上添加和添加新的 EventHandlers 但永远不要删除它们。每次计时器再次启动时,所有前一个都会被触发。如果您实现计数器,您可以重现此行为,然后您将看到每个新添加和引发的事件都会加倍。(编辑:只是因为“new”关键字而感到困惑,但实际上我不会删除答案,因为我很确定在某些情况下这正是问题所在)以下可能有帮助: How to remove all event handlers from an event这是最简单的解决方案:(可以使用委托(delegate)进行打磨)类中声明:private System.Windows.Threading.DispatcherTimer P5DispatcherHelpsystemTimer = new System.Windows.Threading.DispatcherTimer();private EventHandler P5DispatcherTimerHandler;调度器定时器方法:private void InitializeHelpsystemCronjobs(System.Windows.Controls.Canvas sub_CanvasElement){ P5DispatcherTimerHandler = (sender, e) => P5DispatcherHelpsystemTimerTick(sender, e, sub_CanvasElement); P5DispatcherHelpsystemTimer.Tick += P5DispatcherTimerHandler; P5DispatcherHelpsystemTimer.Interval = new TimeSpan(0, 0, 1); P5DispatcherHelpsystemTimer.Start();}Dispatcher TimerTick 方法:private void P5DispatcherHelpsystemTimerTick(object sender, EventArgs e, System.Windows.Controls.Canvas sub_CanvasElement){ P5DispatcherHelpsystemTimer.Stop(); { // Do stuff } P5DispatcherHelpsystemTimer.Start();}//当某个触发事件或 Action 等发生并且计时器将启动时:InitializeHelpsystemCronjobs(HelpsystemHelpCanvas);//当它停止时的某个地方:P5DispatcherHelpsystemTimer.Stop();P5DispatcherHelpsystemTimer.Tick -= P5DispatcherTimerHandler;(如果你有更复杂的情况,你肯定需要委托(delegate)列表)关于c# - 调度程序计时器触发两次 :(,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26518284/