如何定义消耗计时器的数量

本文关键字:计时器 何定义 定义 | 更新日期: 2023-09-27 17:53:12

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    List<System.Timers.Timer> list = new List<System.Timers.Timer>();
    List<Thread> ltread = new List<Thread>();
    Thread t1;
    System.Timers.Timer tick;
    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            ltread[i]=new Thread(list[i].Start);
            ltread[i].Start();
        }
    }
    void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
    {
        ((System.Timers.Timer)sender).Stop();
        BeginInvoke(new MethodInvoker(() =>
        {
            textBox1.Text += "I have ended'r'n";
        }));
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
           tick = new System.Timers.Timer();
            tick.Interval = 3000;
            tick.Elapsed+=new System.Timers.ElapsedEventHandler(OnTimer);
            ltread.Add(t1);
            list.Add(tick);
        }
    }
}

如何获得已经过的计时器的编号?

如何定义消耗计时器的数量

你是这个意思吗?

int index = list.IndexOf(((System.Timers.Timer)sender));

不幸的是,System.Timers.Timer没有给您附加传递给Elapsed事件处理程序的任意值的能力。你可以用System.Threading.Timer来做,尽管它需要对你的代码做一点修改。

你的创建代码看起来像这样:

for (int i = 0; i < 5; ++i)
{
    var tick = new System.Threading.Timer(TimerTick, i, 3000, 3000);
    list.Add(tick);
}
构造函数的第二个参数是特定于用户的数据,它将传递给回调函数。在本例中,我只是告诉它传递定时器编号。

当然,您的列表必须是List<System.Threading.Timer>

计时器使用回调方法而不是事件。这个回调函数看起来像这样:

void TimerTick(object state)
{
    int timerNumber = (int)state;
    list[timerNumber].Change(Timeout.Infinite, Timeout.Infinite); // stops the timer.
}

如果你的计时器总是只触发一次然后停止,你可以将它们初始化为一次性而不是周期性的。对于System.Timers.Timer,只需将AutoReset属性设置为False。对于System.Threading.Timer,将Timeout.Infinite作为构造函数的最后一个参数传递。如果您这样做了,那么就没有理由在事件处理程序或回调方法中停止计时器。