简体   繁体   English

C#Winforms System.Threading.Timer

[英]C# Winforms System.Threading.Timer

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 InvalidOperationException:在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke

Edit: I thought it is solved but the code still shows error 编辑:我认为它已解决但代码仍显示错误

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() 尝试保存计时器的实例,并在Form_Closing事件中调用timer.Dispose()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM