2

我正在用 C# 编写一个程序,每 15 分钟就会对“google”执行一次 ping 操作。如果 ping 成功,它将在 15 分钟后再次检查(ping),依此类推...如果 ping 不成功,它将执行我的 ISP 的 dailer,并在每 15 分钟后再次检查。

我已经编写了所有代码,但似乎无法将计时器设置为每 15 分钟后重复一次代码。如果有人可以帮助我,我将不胜感激。

这是代码。

using System;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;
using System.Diagnostics;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer.Interval = (4000); //For checking, I have set the interval to 4 sec. It actually needs to be 15 minutes.
        timer.Enabled = true; 
        timer.Start(); 

        Ping ping = new Ping();

        PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"));

        if (pingStatus.Status != IPStatus.Success)
        {
            timer.Tick += new EventHandler(timer1_Tick);
        }

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Process.Start("C:\\WINDOWS\\system32\\rasphone.exe","-d DELTA1");
    }

}
}

这段代码的作用是,如果我的拨号器在我执行这个程序时已经连接——它什么也不做。4秒后甚至不重新检查。但是,如果我运行这个程序时拨号器没有连接,它会立即连接我的拨号器,并在每 4 秒后尝试重新连接拨号器,甚至不检查(ping google)。

我似乎无法正确设置计时器,因为我以前从未使用过计时器功能。如果有人可以帮助我,我将不胜感激。

问候, Shajee A.

4

2 回答 2

14

听起来您只需要在计时器的Tick处理程序中移动您的 ping 代码。像这样:

private void Form1_Load(object sender, EventArgs e)
{
    timer.Interval = 4000;
    timer.Enabled = true; 
    timer.Tick += new EventHandler(timer1_Tick);
    timer.Start(); 
}

private void timer1_Tick(object sender, EventArgs e)
{
    Ping ping = new Ping();
    PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"));

    if (pingStatus.Status != IPStatus.Success)
    {
        Process.Start("C:\\WINDOWS\\system32\\rasphone.exe","-d DELTA1");
    }
}
于 2013-06-10T11:46:21.707 回答
0

如果 ping 失败,则将 timer1_Tick 方法连接到委托,如果成功,则不连接它。每 4 秒调用一次委托。因此,如果第一次测试失败,则每 4 秒调用一次 dailer,如果失败则没有任何反应。

您需要将 time1_Tick 方法连接到委托(无测试)并将测试(ping)放在 timer1_Tick 方法中,以便每 4 秒进行一次测试。

于 2013-06-10T11:51:32.953 回答