如何解决dispachertimer在c#中挂起应用程序?

How to solve the dispachertimer hang the application in c#?

我使用下面的代码在应用程序挂起 30 秒后(即 UI 冻结)自动调用 reporting.But 几秒钟。

如何解决这个不挂的问题。 下面是我的代码

     System.Windows.Threading.DispatcherTimer dispatcherTimer2 = new  
                                        System.Windows.Threading.DispatcherTimer();

  dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
     dispatcherTimer2.Interval = new TimeSpan(0, 0, 30);
     dispatcherTimer2.Start();

    private void dispatcherTimer2_Tick(object sender, EventArgs e)
   {
     automaticreportfunction();

   }

30秒后应用挂起,如何解决

DispatcherTimer 在 Background-Tread 中运行。 Tick-Event中的所有方法都是UI-Tread中的运行。这就是为什么您的应用程序会冻结。您必须将 automaticreportfunction() 移动到后台线程才能使 UI 保持活动状态。

因此你有几个机会。我个人更喜欢 BackgroundWorker 的用法(我知道还有其他方法,但我最喜欢这个)。因此,在您的 Tick-Event 中,您可以执行以下操作:

private void dispatcherTimer2_Tick(object sender, EventArgs e)
{
    DispatcherTimer dispatcherTimer = (DispatcherTimer)sender;
    dispatcherTimer.Stop();
    BackgroundWorker backgroundWorker = new BackgroundWorker();
    backgroundWorker.DoWork += (bs, be) => automaticreportfunction();
    backgroundWorker.RunWorkerCompleted += (bs, be) => dispatcherTimer.Start();
    backgroundWorker.RunWorkerAsync();
}

我也会在您进入 tick-method 时停止计时器,并在 automaticreportfunction 完成后再次重新启动它,否则您可以在执行仍在运行时再次进入该方法。