使用计时器定期更改值

本文关键字:计时器 | 更新日期: 2023-09-27 18:00:02

Hye我是C#的新手,只想手动运行计时器!所以我只想知道我在代码中做错了什么。我只需要在我的计时器里显示一条简单的消息!我的代码是:

public partial class Form1 : Form
{
    System.Timers.Timer time;
    public Form1()
    {
        InitializeComponent();
        time = new System.Timers.Timer();
        time.Interval = 10;
        time.Enabled = true;
        time.Start();
    }
    private void time_Tick(object e, EventArgs ea)
    {
        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine(i);
        }
    }
}

如果我做错了什么,请告诉我。提前谢谢!

使用计时器定期更改值

您忘记监听Elapsed事件。添加:

time.Elapsed += new ElapsedEventHandler(time_Tick); 

对于计时器的初始化,它应该在计时器结束时调用回调函数(此时为10ms)

另请注意,回调函数将每10ms调用一次
如果希望回调函数停止运行,请在回调函数中添加time.Stop();

编辑:

也许使用类System.Windows.Forms.Timer而不是System.Timers.Timer更好。在那里你可以调用你的函数,也可以访问你的文本框。

否则,尝试访问time_Tick中的文本框txt将收到InvalidOperationException。

你不需要一个循环来增加你的值i。只需重新启动计时器并设置新值。您现在要做的是等待ONE勾选(持续1000毫秒),然后开始循环。

例如,这可能是您的方法:

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    private int i = 0;
    private Timer time;
    public Form1()
    {
        InitializeComponent();
        time = new Timer();
        time.Tick += time_Tick;
        time.Interval = 1000;
        time.Start();
    }
    private void time_Tick(object e, EventArgs ea)
    {
        if (i < 100)
        {
            txt.Text = i.ToString();
            i++;
            time.Start();
        }
    }
  }
}