C#-Windows服务-连续Ping请求超时

C#-Windows服务-连续Ping请求超时,c#,service,windows-services,C#,Service,Windows Services,一般来说,我对C#和面向对象编程是新手。我正在创建一个windows服务,每10分钟ping一个IP地址10次 如果10个请求中有7个请求超时(隔离网络漏洞),它将发送电子邮件通知系统已关闭。这部分我做对了 我面临的问题是通知系统已启动 以下是我的代码: protected override void OnStart(string[] args) { eventLog.WriteEntry("Source: Service Started",Eve

一般来说,我对C#和面向对象编程是新手。我正在创建一个windows服务,每10分钟ping一个IP地址10次

如果10个请求中有7个请求超时(隔离网络漏洞),它将发送电子邮件通知系统已关闭。这部分我做对了

我面临的问题是通知系统已启动

以下是我的代码:

protected override void OnStart(string[] args)
        {
                eventLog.WriteEntry("Source: Service Started",EventLogEntryType.SuccessAudit);
                timer.Enabled = true;
                timer.Interval = (10 * 60 * 1000);
                timer.Elapsed += new System.Timers.ElapsedEventHandler(methodStart);


        }

 public void methodStart(object sender, ElapsedEventArgs e)
        {

            Ping p = new Ping();
            PingReply r;
            string s = "SYSTEM-IP-ADDRESS";
            int upCounter=0;
            int downCounter = 0;

            bool sysDown = false;
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    r = p.Send(s);
                    if (r.Status == IPStatus.Success)
                    {
                        eventLog.WriteEntry("Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
                         + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n", EventLogEntryType.SuccessAudit);
                        upCounter++;

                    }
                    else
                    {

                        downCounter++;
                    }
                }

                if(downCounter>=7)
                {
                    //LOG ENTRY
                    eventLog.WriteEntry("Unable to reach the system after 7 Timeouts! Email notification Sent.", EventLogEntryType.FailureAudit);

                    // EMAIL NOTIFICATION


                    downCounter = 0;
                }
                else
                {
                    sysDown = false;

                }

            }
            catch (Exception ex)
            {
                //EXCEPTION HANDLING

            }
            loopCounter++;

            if(sysDown==false && loopCounter>2)
            {
                eventLog.WriteEntry("The Tool Is Up Email Notification Sent", EventLogEntryType.SuccessAudit);

                // EMAIL NOTIFICATION

                loopCounter = 0;
            }

        }   
protected override void OnStart(字符串[]args)
{
WriteEntry(“源:服务已启动”,EventLogEntryType.SuccessAudit);
timer.Enabled=true;
定时器间隔=(10*60*1000);
timer.appead+=新系统.Timers.ElapsedEventHandler(methodStart);
}
public void methodStart(对象发送方,ElapsedEventArgs e)
{
Ping p=新Ping();
pingr;
字符串s=“系统IP地址”;
int upCounter=0;
int下行计数器=0;
bool sysDown=false;
尝试
{
对于(int i=0;i<10;i++)
{
r=p.Send(s);
if(r.Status==IPStatus.Success)
{
eventLog.WriteEntry(“Ping到”+s.ToString()+“[“+r.Address.ToString()+”]”+“成功”
+“Response delay=“+r.RoundtripTime.ToString()+”ms“+”\n”,EventLogEntryType.SuccessAudit);
upCounter++;
}
其他的
{
下行计数器++;
}
}
如果(下行计数器>=7)
{
//日志条目
eventLog.WriteEntry(“7次超时后无法访问系统!已发送电子邮件通知。”,EventLogEntryType.FailureAudit);
//电子邮件通知
下行计数器=0;
}
其他的
{
sysDown=false;
}
}
捕获(例外情况除外)
{
//异常处理
}
loopCounter++;
if(sysDown==false&&loopCounter>2)
{
WriteEntry(“工具已发送电子邮件通知”,EventLogEntryType.SuccessAudit);
//电子邮件通知
循环计数器=0;
}
}   
我试图实现的是,ping超时7=>次,并发送一封电子邮件声明它已关闭。如果系统在接下来的2次执行期间启动,请发送一封电子邮件,说明系统已启动(我的代码每2次执行发送一封电子邮件,说明系统已启动)

如何做到这一点

更新1:我有电子邮件逻辑

更新2:Vibhav Ramcharan的解决方案会在每次执行startMethod()时触发系统启动通知。

系统停机通知的阈值为70%,即在一次执行期间连续出现7次ping故障

假设,当系统崩溃时。将触发一封电子邮件,通知系统故障

当系统启动时,执行成功两次。发送电子邮件通知系统已启动


上述代码在每个methodStart()上触发系统启动电子邮件。最后是垃圾邮件。

好的,阅读您的评论,我认为您需要在方法之外声明一个静态int。 例如:

如果需要执行该方法两次,则应从methodStart提取所有方法(示例名称:startUpMethod(),然后在methodStart中调用startUpMethod()); 当您想再次调用该方法时(不管它是否在同一个方法中),可以再次调用startUpMethod()。 这称为递归调用。 例如


你应该注意无限循环

根据我的理解,你需要跟踪两次成功的执行,并在失败后发送电子邮件。我在下面的代码中添加了注释

    protected override void OnStart(string[] args){

        var timer = new Timer
        {
            Enabled = true,
            Interval = (10 * 60 * 1000)
        };
        timer.Elapsed += new System.Timers.ElapsedEventHandler(methodStart);
    }

    private int loopCounter = 0;
    bool sysDown = false;

    // Used to count the number of successful executions after a failure.
    int systemUpAfterFailureCount = 0;

    public void methodStart(object sender, ElapsedEventArgs e)
    {

        Ping p = new Ping();
        PingReply r;
        string s = "SYSTEM-IP-ADDRESS";
        int upCounter = 0;
        int downCounter = 0;


        try
        {
            for (int i = 0; i < 10; i++)
            {
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                    upCounter++;
                else
                    downCounter++;
            }

            if (downCounter >= 7)
            {
                // LOG ENTRY
                // EMAIL NOTIFICATION
                downCounter = 0;
                // The system has failed
                sysDown = true;
            }
            else
            {
                // Before changing the sysDown flag, check if the system was previously down
                // This is the first successful execution after the failure
                if (sysDown)
                    systemUpAfterFailureCount++;

                // This will allow systemUpAfterFailureCount to increase if it is Ex: 1 and sysDown = false (Your success execution limit is 2, which we control at the IF block below)
                if (systemUpAfterFailureCount > 1)
                    systemUpAfterFailureCount++;

                sysDown = false;
            }

        }
        catch (Exception ex)
        {
            //EXCEPTION HANDLING
        }

        loopCounter++;

        // Check if the system is down, if it is up execute the following code for a maximum of 2 executions.
        if (sysDown==false && systemUpAfterFailureCount <= 2) 
        {
            // LOG ENTRY
            loopCounter = 0;

            // Send email for successful executions after a failure, limited to 2.
            if (systemUpAfterFailureCount <= 2)
            {
                // EMAIL NOTIFICATION
            }

            // After two successful executions have occured, reset the counter
            if (systemUpAfterFailureCount == 2)
            {
                systemUpAfterFailureCount = 0;
            }
        }
    }
protected override void OnStart(字符串[]args){
var定时器=新定时器
{
启用=真,
间隔=(10*60*1000)
};
timer.appead+=新系统.Timers.ElapsedEventHandler(methodStart);
}
私有int循环计数器=0;
bool sysDown=false;
//用于计算失败后成功执行的次数。
int systemUpAfterFailureCount=0;
public void methodStart(对象发送方,ElapsedEventArgs e)
{
Ping p=新Ping();
pingr;
字符串s=“系统IP地址”;
int upCounter=0;
int下行计数器=0;
尝试
{
对于(int i=0;i<10;i++)
{
r=p.Send(s);
if(r.Status==IPStatus.Success)
upCounter++;
其他的
下行计数器++;
}
如果(下行计数器>=7)
{
//日志条目
//电子邮件通知
下行计数器=0;
//系统出故障了
sysDown=true;
}
其他的
{
//在更改sysDown标志之前,请检查系统以前是否已关闭
//这是失败后的第一次成功执行
if(sysDown)
systemUpAfterFailureCount++;
//这将允许systemUpAfterFailureCount在Ex:1且sysDown=false时增加(您的成功执行限制为2,我们在下面的if块中控制该限制)
如果(systemUpAfterFailureCount>1)
systemUpAfterFailureCount++;
sysDown=false;
}
}
捕获(例外情况除外)
{
//异常处理
 public void public void methodStart(object sender, ElapsedEventArgs e){
     startUpMethod();
 }

 public void startUpMethod()
 {
      //do something
      if(repeat)
         startUpMethod()
 }
    protected override void OnStart(string[] args){

        var timer = new Timer
        {
            Enabled = true,
            Interval = (10 * 60 * 1000)
        };
        timer.Elapsed += new System.Timers.ElapsedEventHandler(methodStart);
    }

    private int loopCounter = 0;
    bool sysDown = false;

    // Used to count the number of successful executions after a failure.
    int systemUpAfterFailureCount = 0;

    public void methodStart(object sender, ElapsedEventArgs e)
    {

        Ping p = new Ping();
        PingReply r;
        string s = "SYSTEM-IP-ADDRESS";
        int upCounter = 0;
        int downCounter = 0;


        try
        {
            for (int i = 0; i < 10; i++)
            {
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                    upCounter++;
                else
                    downCounter++;
            }

            if (downCounter >= 7)
            {
                // LOG ENTRY
                // EMAIL NOTIFICATION
                downCounter = 0;
                // The system has failed
                sysDown = true;
            }
            else
            {
                // Before changing the sysDown flag, check if the system was previously down
                // This is the first successful execution after the failure
                if (sysDown)
                    systemUpAfterFailureCount++;

                // This will allow systemUpAfterFailureCount to increase if it is Ex: 1 and sysDown = false (Your success execution limit is 2, which we control at the IF block below)
                if (systemUpAfterFailureCount > 1)
                    systemUpAfterFailureCount++;

                sysDown = false;
            }

        }
        catch (Exception ex)
        {
            //EXCEPTION HANDLING
        }

        loopCounter++;

        // Check if the system is down, if it is up execute the following code for a maximum of 2 executions.
        if (sysDown==false && systemUpAfterFailureCount <= 2) 
        {
            // LOG ENTRY
            loopCounter = 0;

            // Send email for successful executions after a failure, limited to 2.
            if (systemUpAfterFailureCount <= 2)
            {
                // EMAIL NOTIFICATION
            }

            // After two successful executions have occured, reset the counter
            if (systemUpAfterFailureCount == 2)
            {
                systemUpAfterFailureCount = 0;
            }
        }
    }
 public void methodStart(object sender, ElapsedEventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s = "SYSTEM-IP-ADDRESS";
                try
                {
                    for (int i = 0; i < 10; i++)
                    {
                        r = p.Send(s);
                        if (r.Status == IPStatus.Success)
                        {
                             SuccessNoti();

                       }
                        else
                        {

                            UnsuccessfulNoti();
                        }
                    }
                }
                catch (Exception ex)
                {
                    UnsuccessfulNoti();
                }

                }

            } 

             public void SuccessNoti()
            {
                if ((string.Compare(status, "Down", false) == 0) && Successcount >= 7)
                {
                    using (MailMessage mail = new MailMessage())
                    {
                        using (SmtpClient SmtpServer = new SmtpClient(smtp))
                        {
                        //  EMAIL NOTIFICATION

                            Successcount = 0;
                            status = null;
                        }
                    }
                }
                else
                {
                    if (string.Compare(status, "Down", false) == 0)
                    {
                        Successcount = Successcount + 1;
                    }
                }
            }

             public void sendfailureNotofication()
            {
                if (failureCount >= 7 && !(string.Compare(status, "Down", false) == 0))
                {

                    status = "Down";
                    using (MailMessage mail = new MailMessage())
                    {
                        using (SmtpClient SmtpServer = new SmtpClient(smtp))
                        {
                        //  EMAIL NOTIFICATION

                            failureCount = 0;
                            status = "Down";
                        }
                    }
                }
                else
                {
                    if (!(string.Compare(status, "Down", false) == 0))
                    {
                        failureCount = failureCount + 1;
                    }
                }


            }