Mothy
Mothy

Reputation: 416

System.Timers.Timer hangs the Windows Forms application in c#

The code below shows a timer that ticks every 100* 1000(milliseconds) to show a pop up message for registration.The below code is working but unfortunately my application gets hang after some time.

I have searched in google and stackoverflow for this answer.But i couldnt find a correct answer to make my application work without getting hanged.

        private System.Timers.Timer register_Timer = new System.Timers.Timer();

        register_Timer.Interval = (100 * 1000);
        register_Timer.Elapsed += new ElapsedEventHandler(register_Timer_Tick);     
        register_Timer.SynchronizingObject = this;            
        register_Timer.AutoReset = true;       
        register_Timer.Enabled = true;

        System.GC.KeepAlive(register_Timer);

        private void register_Timer_Tick(object sender, EventArgs e)
              {
                //Pop up to show register message
              }

Upvotes: 0

Views: 2898

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 133975

The application hangs because you're doing a popup (I assume a MessageBox or some other modal dialog box). Of course the application is going to hang. You're putting a modal dialog up in the UI thread.

The problem isn't with the timer, but with your application design.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941237

    register_Timer.SynchronizingObject = this; 

This completely defeats the reason for using System.Timers.Timer. It prevents the Elapsed event handler from being raised on a threadpool thread, the property ensures it will run on the UI thread. Which is what you wanted.

But you still get all the disadvantages of that Timer class. Particularly its habit for swallowing exceptions without a diagnostic is very ugly. As well as continuing to raise the Elapsed event after the form is closed, ensuring this cannot happen is a very difficult problem to solve, there are two inherent race conditions. .NET 1.0 had some design mistakes related to threading, this was one of them.

Just don't do this, use a System.Windows.Forms.Timer instead. It will work exactly like your timer, minus all the disadvantages.

Upvotes: 6

Related Questions