Wywoływanie funkcji w odstępach czasu można przeprowadzić na podstawie Timera.
using System;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
// Cykliczne wywoływanie funkcji co 1s
private Timer timer1;
int counter = 0;
public Form1()
{
InitializeComponent();
timer1 = new Timer();
timer1.Tick += new EventHandler(timer2_Tick);
timer1.Interval = 1000; // in miliseconds
timer1.Start();
}
private void timer2_Tick(object sender, EventArgs e)
{
if (counter == 10) timer1.Stop();
label1.Text = counter.ToString();
counter++;
}
}
}
Przykład z dwoma Timerami do wywoływanie funkcji przez określony czas
using System;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
private Timer timer1;
private Timer timer2;
int counter = 0;
public Form1()
{
InitializeComponent();
timer1 = new Timer();
timer2 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 100; // in miliseconds
timer1.Start();
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Interval = 10000; // in miliseconds
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = counter.ToString();
counter++;
}
private void timer2_Tick(object sender, EventArgs e)
{
timer1.Stop();
timer2.Stop();
}
}
}