c# - 每 30 秒重复一次 ping

标签 c# winforms timer ping

我创建了一个 Windows 窗体 应用程序来 ping 一个 IP 地址列表,然后我使用一个 Timer30 秒重复一次 ping .这是我使用的代码:

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();                      
    }

但是我收到了这个错误信息:

Error 1 No overload for 'button1_Click' matches delegate 'System.EventHandler'

我尝试了很多例子,但我不知道如何使用 Timer。这里的问题是什么,或者是否有任何其他方法可以重复 Ping?

最佳答案

请注意,Button.ClickedTimer.Elapsed 具有不同的签名;你,可能,想要

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();
}

或者您可以借助lambda 函数 完全摆脱timer_Elapsed:

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();
}

关于c# - 每 30 秒重复一次 ping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57970823/

相关文章:

C# Winforms DatagridviewCombobox异常字符串无法转换为类

c# - 连续打字时不要引发 TextChanged

java - 应用程序在启动前崩溃

java - Java 中简单的横向卷轴游戏出现滞后

C# 线程和属性

c# - 在 CRM 2011 插件中禁用订单上的价格订单时,需要在提交之前启动交易

c# - 在datagridview中如何使用复选框作为单选按钮?

c# - 在 winforms 生成的 .Designer.cs 文件中修改 Dispose(bool) 时,是否有必要将 Dispose 移动到主代码文件?

c - C中的计时器实现,用于在计时器到期后删除链表中的记录

c# - Fluent NHibernate (ASP.NET MVC) 中的枚举类型不匹配