2

I hav tried the below code for checking reports from server in every 30seconds,but after 30seconds tick,The application hangs for several seconds.How to avoid the Hanging problem. The below code am tried,what change want to given in this?

System.Windows.Threading.DispatcherTimer dispatcherTimer2 = new System.Windows.Threading.DispatcherTimer();
 dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
 dispatcherTimer2.Interval = new TimeSpan(0, 0, 30);


Public void dispatcherTimer2_Tick(object sender, EventArgs e)
{
   dispatcherTimer2.start();
    //code for function call autoreport();
}
NvadeepKumar
  • 25
  • 1
  • 7
  • What does that `autoreport` does? Does it works with UI or non UI elements? If latter, you don't need a `DispatcherTimer` you can use `System.Timers.Timer` – Sriram Sakthivel Feb 20 '15 at 06:16
  • @SriramSakthivel: The autoreport works with UI,am used the Syatem.Timer.Timer, that time also hangs several seconds – NvadeepKumar Feb 20 '15 at 06:20

3 Answers3

4

DispatcherTimer callback is executed on main UI thread and blocks it. Use System.Threading.Timer and if you need to update user interface from timer callback use one of Dispatcher.Invoke overloads. In code something like this

public partial class MainWindow : Window
{
    System.Threading.Timer timer;
    public MainWindow()
    {
        InitializeComponent();
        timer = new System.Threading.Timer(OnCallBack, null, 0, 30 * 1000);
    }


    private void OnCallBack(object state)
    {
        //code to check report 
        Dispatcher.Invoke(() =>
        {
            //code to update ui
            this.Label.Content = string.Format("Fired at {0}", DateTime.Now);
        });
    }
}
Dima Korn
  • 546
  • 3
  • 5
2
var timer = new System.Threading.Timer(
    delegate
    {
        //--update functions here (large operations)
        var value = Environment.TickCount;

        //--run update using interface thread(UI Thread)

        //--for WinForms
        Invoke(
            new Action(() =>
            {
                //--set the value to UI Element
            }));

        //--for WPF
        Dispatcher.Invoke(
            new Action(() =>
            {
                //--set the value to UI Element
            }), null);
    });
var period = TimeSpan.FromSeconds(30);
timer.Change(period, period);

I hope it helps.

denys-vega
  • 3,522
  • 1
  • 19
  • 24
0

This is worked for me

 public Form1()
    {
        InitializeComponent();

        var timer = new System.Timers.Timer(500);
        // Hook up the Elapsed event for the timer.
        timer.Elapsed += timer_Elapsed;
        timer.Enabled = true;
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Invoke(
          new Action(() =>
          {
              label1.Text += "Test Label";
              Application.DoEvents();
          }));
    }
Ajay
  • 444
  • 2
  • 9