1

I am having trouble with this code being used in multiple window forms:

  private void Window_Load(object sender, EventArgs e)
  {   
     new System.Threading.Timer((state) => 
     { 
         BeginInvoke((Action)delegate() 
         {
             if (!CurrentTimeDate.IsHandleCreated) return;
             CurrentTimeDate.Text = "    " +    DateTime.Now.ToString("hh:mm:ss") + "  " + DateTime.Now.ToShortDateString(); 
         }); 

     }, null, 0, 1000);
  }

When I show the form at first click, it works well, and then I press close button of the window form. I click again the button to show the form again then it shows this error:

InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Edit: I thought it is solved but the code still shows error

1
  • 3
    There is no point whatsoever in using a System.Timers.Timer and then use BeginInvoke() in the Elapsed event handler. Use a regular Winforms timer for the exact same outcome, minus the crash. Drop it from the toolbox onto the form, the timer will be automatically disposed when the user closes the form, thus automatically stopping it as well. Commented Mar 8, 2014 at 16:28

1 Answer 1

3

I think it's the timer which continue to run, after you're form has been closed. Try save the instance of the timer, and in the Form_Closing event call timer.Dispose()

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked but the application does not close completely. How do I fix it?
Sounds like there still some threads running in the background... The Dispose methods closes the timer's thread, but there might me other threads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.