I created a Windows Forms application to ping a list of Ip addresses, then i used a Timer
to repeat the ping every 30
seconds. This is the code i used:
private System.Timers.Timer timer;
public Form1()
{
InitializeComponent();
timer = new System.Timers.Timer();
timer.Interval = 30000;
timer.Enabled = true;
timer.Elapsed += button1_Click;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
pingResults.Clear();
ipAddress.Add("10.100.1.1");
ipAddress.Add("10.100.1.2");
ipAddress.Add("10.100.1.3");
ipAddress.Add("10.100.1.4");
ipAddress.Add("10.100.1.5");
ipAddress.Add("10.100.1.100");
for (int i = 1; i < 7; i++)
{
pictureBoxList.Add((PictureBox)Controls.Find("pictureBox" + i, true)[0]);
}
Parallel.For(0, ipAddress.Count(), (i, loopState) =>
{
Ping ping = new Ping();
PingReply pingReply = ping.Send(ipAddress[i].ToString());
this.BeginInvoke((Action)delegate()
{
pictureBoxList[i].BackColor = (pingReply.Status == IPStatus.Success) ? Color.Green : Color.Red;
});
});
}
private void button1_Click(object sender,ElapsedEventArgs e )
{
backgroundWorker1.RunWorkerAsync();
}
But i got this error message:
Error 1 No overload for 'button1_Click' matches delegate 'System.EventHandler'
I tried a lot of examples but i didn't get how to use the Timer
. what is the problem here or is there any other way to repeat the Ping?
Please, note that Button.Clicked
and Timer.Elapsed
have different signatures; you, probably, want
public Form1()
{
InitializeComponent();
timer = new System.Timers.Timer();
timer.Interval = 30000;
timer.Enabled = true;
timer.Elapsed += timer_Elapsed; // not button1_Click
}
...
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
Or you can get rid of timer_Elapsed
at all with a help of lambda function:
public Form1()
{
InitializeComponent();
timer = new System.Timers.Timer();
timer.Interval = 30000;
timer.Enabled = true;
timer.Elapsed += (s, e) => {backgroundWorker1.RunWorkerAsync();};
}
...
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}