【问题标题】:DispatcherTimer stop when Window application hangedWindow 应用程序挂起时 DispatcherTimer 停止
【发布时间】:2012-12-10 14:45:12
【问题描述】:

我编写了这个函数来更新每一秒的计时器时间。

DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = TimeSpan.FromSeconds(1.0);

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
            ApplicationVariables.ServerDateTime = CurrentDT = CurrentDT.AddSeconds(1);     
}

但是,如果我的应用程序挂起一段时间,那么应用程序计时器会在那个时候停止,并且在响应应用程序计时器启动并从上次开始之后,而不是添加应用程序挂起时间和最后一次以显示实际时间。即使应用程序挂起,请建议我如何保持计时器开启。

我正在使用 BackgroundWorker 对象来维护应用程序挂起状态。

当我的应用程序尝试初始化 fujitsu reader 的对象时,它通常会挂起。

更多详情请查看附件。

【问题讨论】:

  • 对于导致应用挂起的蹩脚代码的唯一真正治愈方法是停止使用该蹩脚代码。
  • 是的——就像@HansPassant 说的,修复你的GUI,让它不会挂起。不要在你的 GUI 线程中挂东西。
  • 感谢回复,但是当我初始化 fujitsu 驱动程序对象以扫描手掌时,它需要 2 到 3 秒,因为当时计时器停止并在完全重新初始化对象后重新启动。
  • 从非 GUI 线程创建/初始化/运行驱动程序,以便它可以在需要时阻塞。这是在驱动程序完成之前避免填充表单计时器的唯一干净方法。我能看到的唯一其他方法是 Bodges 可能会或可能不会很好地满足您的全部要求。

标签: c# .net wpf multithreading


【解决方案1】:

我建议使用非调度程序计时器来执行您的任务并在必要时通过调用来更新 UI。

public System.Threading.Timer MyTimer { get; set; }

this.MyTimer = new System.Threading.Timer(new TimerCallback(MyTimer_CallBack), null, 1000, 1000);

void MyTimer_CallBack(object State)
{
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
  ApplicationVariables.ServerDateTime = CurrentDT = CurrentDT.AddSeconds(1); 
});
}

【讨论】:

  • UI 挂起时调用也会挂起。
  • @usr 是的,但它不会延迟计时器,因为它使用BeginInvoke。实际的 UI 任务将被延迟,但计时器将始终以快乐的方式进行。
猜你喜欢
  • 2014-11-05
  • 2020-06-21
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
相关资源
最近更新 更多