c#中的进程计时器故障 [英] trouble in process timer in c#

查看:64
本文介绍了c#中的进程计时器故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我在计时器方面遇到麻烦。你能帮助我吗? plzzz。 :d。

我正在尝试使用计时器ping IP。



  private   void  timer_status_Tick( object  sender,EventArgs e)
{

string ip_ping;
if (counter > =(dtg_IP.Rows.Count - 1 ))
{
counter = 0 ;
}
else
{
ip_ping = Convert.ToString(dtg_IP.Rows [counter] .Cells [ 0 ]值);
Ping ping = new Ping();
PingReply pingresult = ping.Send(ip_ping);
if (pingresult.Status.ToString()== 成功
{
dtg_IP.Rows [counter] .Cells [ 4 ]。值= Online;
}
else
{
dtg_IP.Rows [counter] .Cells [ 4 ]。值= offline;
}
counter ++;
}
}



但是当启用计时器时,所有功能都停止等待计时器已经完成处理。你能告诉我怎么解决吗?

非常感谢你:)。

解决方案

首先你应该不依赖在Ping上作为确定服务器是否可用的技术,至少除非它们是内部的。许多外部服务器禁用ping以避免恶意垃圾邮件。



但是假设您可以使用该技术而且因为您写了'因为我有很多我不知道的事情'这是一个可以完成任务的免费赠品。并且通常使用计时器来生成线程,因为使用线程甚至任务可以使它更加平滑并且在更短的时间内获得更多结果等,这只是一个快速的启动,试图避免最常见的陷阱。



 静态  void  Main(  string  [] args)
{
try
{
var hosts = new [] { www.google.dk www。 msn.dk};
使用 var pingTime = new PingTime(hosts))
{
pingTime.PingResultIn + = pingTime_PingResultIn;
pingTime.Start();
Thread.Sleep( 15000 );
Console.WriteLine( 停止);
pingTime.Stop();
Console.WriteLine( 已停止);
}

}
catch (例外情况)
{
Console.WriteLine( 发生异常:\\\\ n + ex.ToString());
}

Console.WriteLine( \\ n按任意键退出);
Console.ReadLine();
}

静态 void pingTime_PingResultIn( object sender,PingResultEventArgs e)
{
string message = Ping to host' + e.Host + ' +(e.IsInError? failed:< span class =code-string> succeeded);
消息+ = \\\\ nHost +(e.IsOnline?< span class =code-string> online OFFLINE);
Console.WriteLine( {0} {1},DateTime.UtcNow.ToString ( HH:mm:ss.fff),message);
}

public class PingResultEventArgs:EventArgs
{
public string 主机{ get ; set ; }
public bool IsOnline { get ; set ; }
public 异常异常{ get ; set ; }

public bool IsInError
{
< span class =code-keyword> get

{
return 异常!= ;
}
}
}

public class PingTime:IDisposable
{
private string [] _hosts;
private bool _run = false ;
private bool _stop = false ;
private bool _timeTickExecuting = false ;
私人计时器_time;

public event EventHandler< pingresulteventargs> PingResultIn;

public PingTime( string [] hostsToPing)
{
if (hostsToPing == null || hostsToPing.Length == 0
throw new ArgumentException( 必须在实例化时提供主机ping);
_hosts = hostsToPing;
_time = new 计时器(_timeTicked, null ,Timeout.Infinite,Timeout.Infinite);
}

public void 开始( int pingIntervalInMilliseconds = 1000
{
_stop = false ;
_run = true ;
_time.Change(pingIntervalInMilliseconds,pingIntervalInMilliseconds);
}

public void Stop(){
_stop = true ;
while (_ run)
Thread.Sleep( 250 );
}

private void _timeTicked( object state)
{
if (_ timeTickExecuting) return ;
_timeTickExecuting = true ;
尝试
{
如果(_stop)
{
_time.Change(Timeout.Infinite,Timeout.Infinite);
_run = false ;
return ;
}
lock (_ hosts)
{
foreach string host in _hosts)
{
if (_stop) break ;
PingHost(主持人);
}
}
}
最后
{
_timeTickExecuting = ;
}
}

私有 void PingHost( 字符串主持人)
{
尝试
{
var ping = new Ping();
PingReply reply = ping.Send(host, 3000 );

if (reply.Status == IPStatus.Success)
{
OnPingResultIn( this new PingResultEventArgs {Host = host,IsOnline = true }) ;
return ;
}
OnPingResultIn( this new PingResultEventArgs {Host = host,IsOnline = false });
}
catch (例外情况)
{
OnPingResultIn( this new PingResultEventArgs {Exception = ex,Host = host});
}
}

私有 void OnPingResultIn( object sender,PingResultEventArgs e)
{
var handler = PingResultIn;
if (handler!= null
handler(sender,e);
}

public void Dispose()
{
OnDispose( true );
}

受保护 void OnDispose( bool disposing)
{
if (!disposing)返回;
if (_time == null return ;
_time.Dispose();
_time = null ;
}
}





你的回家任务是重写它以使用WebRequest类而不是Ping; )


Hi everybody!!!
I am trouble with timer. Can you help me? plzzz. :D.
I am trying use timer to ping IP.

private void timer_status_Tick(object sender, EventArgs e)
      {

          string ip_ping;
          if (counter >= (dtg_IP.Rows.Count - 1))
          {
              counter = 0;
          }
          else
          {
              ip_ping = Convert.ToString(dtg_IP.Rows[counter].Cells[0].Value);
              Ping ping = new Ping();
              PingReply pingresult = ping.Send(ip_ping);
              if (pingresult.Status.ToString() == "Success")
              {
                  dtg_IP.Rows[counter].Cells[4].Value = "Online";
              }
              else
              {
                  dtg_IP.Rows[counter].Cells[4].Value = "offline";
              }
              counter++;
          }
      }


but when enable timer, all functions are stopped to wait timer has finished processing. Can you tell me how to solve it?
Thank you very much :).

解决方案

Well first of all you should propably not rely on Ping as a technology to determine if a server is available at least unless they're internal. Many external servers disable ping to avoid malicious spamming.

But presuming you can use that technology and because you wrote 'because i have so many things that i do not know' here's a freebie that could do the task. and generally use the timer to spawn threads, of cause using threads or even tasks could make it more sleak and get more results in less time etc, this just a quick whipup, trying to avoid the most common pitfalls.

static void Main(string[] args)
        {
            try
            {
                var hosts = new[] { "www.google.dk", "www.msn.dk" };
                using (var pingTime = new PingTime(hosts))
                {
                    pingTime.PingResultIn += pingTime_PingResultIn;
                    pingTime.Start();
                    Thread.Sleep(15000);
                    Console.WriteLine("Stopping");
                    pingTime.Stop();
                    Console.WriteLine("Stopped");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured:\r\n" + ex.ToString());
            }

            Console.WriteLine("\r\nPress any key to exit");
            Console.ReadLine();
        }

        static void pingTime_PingResultIn(object sender, PingResultEventArgs e)
        {
            string message = "Ping to host '" + e.Host + "' " + (e.IsInError ? "failed" : "succeeded");
            message += "\r\nHost " + (e.IsOnline ? "online" : "OFFLINE");
            Console.WriteLine("{0} {1}", DateTime.UtcNow.ToString("HH:mm:ss.fff"), message);
        }

public class PingResultEventArgs : EventArgs
    {
        public string Host { get; set; }
        public bool IsOnline { get; set; }
        public Exception Exception { get; set; }

        public bool IsInError
        {
            get
            {
                return Exception != null;
            }
        }
    }

    public class PingTime : IDisposable
    {
        private string[] _hosts;
        private bool _run = false;
        private bool _stop = false;
        private bool _timeTickExecuting = false;
        private Timer _time;
        
        public event EventHandler<pingresulteventargs> PingResultIn;

        public PingTime(string[] hostsToPing)
        {
            if (hostsToPing == null || hostsToPing.Length == 0)
                throw new ArgumentException("Must supply hosts to ping at instantiation time");
            _hosts = hostsToPing;
            _time = new Timer(_timeTicked,null, Timeout.Infinite, Timeout.Infinite);
        }

        public void Start(int pingIntervalInMilliseconds = 1000)
        {
            _stop = false;
            _run = true;            
            _time.Change(pingIntervalInMilliseconds, pingIntervalInMilliseconds);            
        }

        public void Stop(){
            _stop = true;
            while(_run)
                Thread.Sleep(250);
        }
        
        private void _timeTicked(object state)
        {
            if (_timeTickExecuting) return;
            _timeTickExecuting = true;
            try
            {
                if (_stop)
                {
                    _time.Change(Timeout.Infinite, Timeout.Infinite);
                    _run = false;
                    return;
                }
                lock (_hosts)
                {
                    foreach (string host in _hosts)
                    {
                        if (_stop) break;
                        PingHost(host);
                    }
                }
            }
            finally
            {
                _timeTickExecuting = false;
            }
        }

        private void PingHost(string host)
        {
            try
            {
                var ping = new Ping();
                PingReply reply = ping.Send(host, 3000);
                
                if (reply.Status == IPStatus.Success)                   
                {
                    OnPingResultIn(this, new PingResultEventArgs{ Host = host, IsOnline = true });
                    return;
                }
                OnPingResultIn(this, new PingResultEventArgs { Host = host, IsOnline = false });
            }
            catch (Exception ex)
            {
                OnPingResultIn(this, new PingResultEventArgs { Exception = ex, Host = host });
            }
        }

        private void OnPingResultIn(object sender, PingResultEventArgs e)
        {
            var handler = PingResultIn;
            if (handler != null)
                handler(sender, e);
        }

        public void Dispose()
        {
            OnDispose(true);
        }

        protected void OnDispose(bool disposing)
        {
            if (!disposing) return;
            if (_time == null) return;
            _time.Dispose();
            _time = null;
        }
    }



Your take home task will be to rewrite it to use WebRequest class instead of Ping ;)


这篇关于c#中的进程计时器故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆