如何使用计时器 [英] How to use timer

查看:78
本文介绍了如何使用计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用计时器?
我有一个表格,每当它加载当前时间时,都应该显示
并自动更新.我尝试使用下面的代码,但显示此错误.
跨线程操作无效:从创建该线程的线程以外的线程访问控件"label5"."
很抱歉傻的问题,但我是C#的新手. :)

how to use timer??
i have a form and whenever it load the current time should display
and update itself automatically. i try to use the code below but its showing this error.
"Cross-thread operation not valid: Control ''label5'' accessed from a thread other than the thread it was created on."
sorry for silly question but i m new to c#. :)

private void start_form_Load_1(object sender, EventArgs e)
{
    System.Timers.Timer timerClock = new System.Timers.Timer();
    timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
    timerClock.Interval = 1000;
    timerClock.Enabled = true;
}

public void OnTimer(Object source, ElapsedEventArgs e)
{
    label5.Text = DateTime.Now.ToString();
}



[更正了一些代码格式]



[Corrected some code formatting]

推荐答案

您收到的上一个答案是错误的.
您可以通过一种非常简单的方法来做到这一点.
您只需要使用System.Windows.Forms.Timer而不是System.Timers.Timer.
仅此而已!


而且,当然,事件应该是Tick而不是OnTimer Elapsed.
The previous answer you received is wrong.
You can do it in a very easy way.
You only need to use a System.Windows.Forms.Timer instead of your System.Timers.Timer.
That''s All!


And, of course, the event should be Tick instead of OnTimer Elapsed.


private void start_form_Load_1(object sender, EventArgs e)
{   
 System.Timers.Timer timerClock = new System.Timers.Timer();       
 timerClock.Elapsed += new ElapsedEventHandler(OnTimer);    
 timerClock.Interval = 1000;   
 timerClock.Enabled = true;
}
public void timer1_Tick(object sender, EventArgs e)
{   
 label5.Text = DateTime.Now.ToString();
}


计时器在单独的线程上运行.您无法在线程内访问标签属性.

您需要使用BeginInvoke.有关解决方案,请参见此处 [
A timer runs on a separate thread. You cannot access a label property within the thread.

You need to use BeginInvoke. For a solution see here[^].


这篇关于如何使用计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆