C#.net中具有不同间隔的多个计时器

我希望不同的计时器具有不同的输入间隔。例如,如果我输入4,4计时器创建并在4标签中显示时间,其中第一计时器的时间在1秒内变化,第二计时器的时间在2秒内变化,第三计时器的时间在3秒内变化和4tn计时器的时间在4秒内变化。这是我的代码,

string input = textBox2.Text; int n = Convert.ToInt32(input); for (i = 1; i <= n; i++) { Timer timer = new Timer(); timer.Tick += new EventHandler(timer_Tick); timer.Interval = (1000) * (i); timer.Enabled = true; timer.Start(); Label label = new Label(); label.Name = "label"+i; label.Location = new Point(100, 100 + i * 30); label.TabIndex = i; label.Visible = true; this.Controls.Add(label); } private void timer_Tick(object sender, EventArgs e) { label.Text = DateTime.Now.ToString(); } 

但我没有得到任何输出。我能做什么。我使用Windows应用程序。

另一种方式,比Bala R显示给你的是字典(dict)中的变量引用,用于定时器和标签对,以及通过发送者引用访问事件处理程序(完整源代码,带有2个文本框和一个按钮,第二个文本框)包含文本“3”),希望它会有所帮助:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ProjectDocumentationWorkspace.UI { public partial class MainForm : Form { private Dictionary dict = new Dictionary(); public MainForm() { InitializeComponent(); } private void CreateTimers() { string input = textBox2.Text; int n = Convert.ToInt32(input); for (int i = 1; i <= n; i++) { Timer timer = new Timer(); timer.Tick += new EventHandler(timer_Tick); timer.Interval = (1000) * (i); Label label = new Label(); label.Name = "label" + i; label.Location = new Point(100, 100 + i * 30); label.TabIndex = i; label.Visible = true; this.Controls.Add(label); dict[timer] = label; timer.Enabled = true; timer.Start(); } } private void timer_Tick(object sender, EventArgs e) { Timer t = (Timer)sender; DateTime current = DateTime.Now; dict[t].Text = string.Format("{0:00}:{1:00}:{2:00}", current.Hour, current.Minute, current.Second); } private void button1_Click(object sender, EventArgs e) { CreateTimers(); } } } 

我没有看到Timer的Tick事件处理程序如何访问不在其范围内的动态标签。

尝试

  Label label = new Label(); label.Name = "label"+i; label.Location = new Point(100, 100 + i * 30); label.TabIndex = i; label.Visible = true; Timer timer = new Timer(); timer.Tick += (s, e) => label.Text = DateTime.Now.ToString(); timer.Interval = (1000) * (i); timer.Enabled = true; timer.Start(); 

另一种方法是使用Dictionary并在创建它们时为这个字典添加控件,并在计时器的tick处理程序中使用字典来检索其相应的Label