如何实现定时器间隔和启动 [英] How to Implement Timer Interval and Start

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

问题描述

我想要一种情况,当我启动计时器时,它不会在执行操作之前先按其间隔打勾。例如,我想在单击一个间隔为5秒的按钮后在表单上显示标签文本,而是在单击按钮后,在显示标签文本之前有5秒的延迟。我该如何解决这个问题呢?

代码看起来像这样:



I want a situation that when I start my timer, it doesn't tick at its interval first before performing an action. For example, I want to display a label text on my form after I click a button with a 5 second interval but instead after the button is clicked, there is a 5 second delay before the label text is shown. How can I solve this issue?
Code looks something like this:

private void btnSet_Click(object sender, EventArgs e)
{
   timer1.Enabled = true;
   timer1.Start();
   timer1.Interval = 5000;
}

private void timer1_Tick(object sender, EventArgs e)
{
   label1.Text = "Hello";
}

推荐答案

将您的动作编写为函数并在计时器启动前调用该函数



你的代码可能是这样的



Write your action as a function and call the function before the timer starts

Your code is probably like this

timer.Start();

void timer_click()
{
    // some code
}





将其更改为





change it to

myFunction();
timer.Start();

void timer_click()
{
    myFunction();
}
void myFunction()
{
    // some code
}


尝试使用以下代码:

Try with below code:
private void btnSet_Click(object sender, EventArgs e)
{
   timer1.Enabled = true;
   timer1.Interval = 5000;
   timer1.Tick += new EventHandler(timer1_Tick);
   timer1.Start();
   
}
 
private void timer1_Tick(object sender, EventArgs e)
{
   label1.Text = "Hello";
}


您可以通过声明内联代表来执行此操作:



You can do this by declaring an inline delegate like:

private void btnSet_Click(object sender, EventArgs e)
{
   var t = new Timer();
   t.Interval = 5000;
   t.Tick += (s, e) =>
   {
       label1.Text = "Hello";
       t.Stop();
   };
   t.Start();
}





其中 s,e 两个参数对象发件人,EventArgs e


这篇关于如何实现定时器间隔和启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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