Search code examples
c#wpfmultithreadingasynchronousdispatchertimer

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


am used the below code for automatically call for reporting.But after 30seconds the application hangs(i.e UI is freeze)for several seconds.

How to solve this without hanging problem. below is my code

     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();

   }

After 30seconds it hangs the application,how to solve this


Solution

  • The DispatcherTimer runs in a Background-Tread. All methods in the Tick-Event are running in the UI-Tread. That's why your application will freezer. You will have to move your automaticreportfunction() to a background-thread in order to keep your UI alive.

    Therefor you have several opportunities. Personally I prefer the usage of a BackgroundWorker (I know that there a other ways, but I like this one most). So in your Tick-Event you can do something like:

    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();
    }
    

    I would also stop the timer when you enter the tick-method and restart it again after your automaticreportfunction finished because otherwise you could enter the method again while your execution still runs.