Launching forms from timer reset function

Hello there,

My requirement is to let's say lanch a form each 10 seconds so I figured I would use a timer.  However, whenever a form is launched by the OnTimer function (which is called whenever the timer resets, it's like the loading of the form never completes and the program is in an unresponsive state.  Note that the code below is not my real world scenario, but I get the same behavior.

Any suggestions or alternatives?
public void start()
    System.Timers.Timer pollTimer = new System.Timers.Timer();
    pollTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
    pollTimer.Enabled = true;
    pollTimer.Interval = 10000;

public void OnTimer(Object source, System.Timers.ElapsedEventArgs e)
    Form1 frm = new Form1();

Open in new window

Who is Participating?
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
The System.Timers.Timer runs in its own thread which is probably the root of your problem.

(1) Switch to System.Window.Forms.Timer (the one in the control toolbox by default)
(2) Use a Delegate and Invoke() from your Elapsed() event to move to the main UI where it is safe to create a form and display it.
Alos: pollTimer  is destroyed as soon as it leaves the start function as the timer is local to the function only. Also try move the Timer object out of the function and onto the form/ class as a member variable.
acicovicAuthor Commented:
For anyone having the same problem, I changed the timer to a System.Windows.Forms timer and everything worked.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.