循环没有冻结程序?

时间:2015-01-05 11:22:16

标签: c#

我正在尝试执行一项看似简单的任务但却无法使我的程序正常运行。

这是在C#中,它的作用是将ping发送到我的服务器并返回它是否响应。我遇到的问题是我希望它在再次尝试之前等待X秒,因此我的服务器没有ping洪水。如果我使用Thread.Sleep使程序等待,它会冻结GUI。这是一个问题,因为GUI告诉用户服务器是否启动。我也尝试过后台工作人员无济于事。有什么想法吗?

我的代码:

  Ping ping = new Ping();
        string x = "go";

        while (x == "go")
        {



            try
            {
                lblS1checking.Text = "Checking...";
                PingReply reply = ping.Send("SERVER NAME", 2000);
                if (reply.Status == IPStatus.Success)
                {
                    lblS1check.BackColor = Color.LimeGreen;
                    lblS1check.Text = "UP";
                }
                else
                {
                    lblS1check.BackColor = Color.Red;
                    lblS1check.Text = "DOWN";
                }

            }
            catch (PingException ex)
            {
                MessageBox.Show("Failed!");

            }
            lblS1checking.Text = "Done.";

            //PROGRAM NEEDS TO SLEEP HERE FOR 30 SECONDS BEFORE TRYING AGAIN. GUI SHOULD NOT FREEZE DURING THIS TIME.

        }

2 个答案:

答案 0 :(得分:2)

您可以使用Ping.SendAsync
这里是MSDN的代码:

using System;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Threading;

namespace Examples.System.Net.NetworkInformation.PingTest
{
    public class PingExample
    {
        public static void Main (string[] args)
        {
            if (args.Length == 0)
                throw new ArgumentException ("Ping needs a host or IP Address.");

            string who = args[0];
            AutoResetEvent waiter = new AutoResetEvent (false);

            Ping pingSender = new Ping ();

            // When the PingCompleted event is raised, 
            // the PingCompletedCallback method is called.
            pingSender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);

            // Create a buffer of 32 bytes of data to be transmitted. 
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes (data);

            // Wait 12 seconds for a reply. 
            int timeout = 12000;

            // Set options for transmission: 
            // The data can go through 64 gateways or routers 
            // before it is destroyed, and the data packet 
            // cannot be fragmented.
            PingOptions options = new PingOptions (64, true);

            Console.WriteLine ("Time to live: {0}", options.Ttl);
            Console.WriteLine ("Don't fragment: {0}", options.DontFragment);

            // Send the ping asynchronously. 
            // Use the waiter as the user token. 
            // When the callback completes, it can wake up this thread.
            pingSender.SendAsync(who, timeout, buffer, options, waiter);

            // Prevent this example application from ending. 
            // A real application should do something useful 
            // when possible.
            waiter.WaitOne ();
            Console.WriteLine ("Ping example completed.");
        }

        private static void PingCompletedCallback (object sender, PingCompletedEventArgs e)
        {
            // If the operation was canceled, display a message to the user. 
            if (e.Cancelled)
            {
                Console.WriteLine ("Ping canceled.");

                // Let the main thread resume.  
                // UserToken is the AutoResetEvent object that the main thread  
                // is waiting for.
                ((AutoResetEvent)e.UserState).Set ();
            }

            // If an error occurred, display the exception to the user. 
            if (e.Error != null)
            {
                Console.WriteLine ("Ping failed:");
                Console.WriteLine (e.Error.ToString ());

                // Let the main thread resume. 
                ((AutoResetEvent)e.UserState).Set();
            }

            PingReply reply = e.Reply;

            DisplayReply (reply);

            // Let the main thread resume.
            ((AutoResetEvent)e.UserState).Set();
        }

        public static void DisplayReply (PingReply reply)
        {
            if (reply == null)
                return;

            Console.WriteLine ("ping status: {0}", reply.Status);
            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine ("Address: {0}", reply.Address.ToString ());
                Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
                Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
                Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
                Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
            }
        }
    }
}

答案 1 :(得分:1)

使用如下所示的计时器: -

 public static void Main()
   {
        // Create a timer with 30 seconds interval.
        aTimer = new System.Timers.Timer(30000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.Enabled = true;
   }

当计时器到期时,将调用方法!

   private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
      try
                {
                    lblS1checking.Text = "Checking...";
                    PingReply reply = ping.Send("SERVER NAME", 2000);
                    if (reply.Status == IPStatus.Success)
                    {
                        lblS1check.BackColor = Color.LimeGreen;
                        lblS1check.Text = "UP";
                    }
                    else
                    {
                        lblS1check.BackColor = Color.Red;
                        lblS1check.Text = "DOWN";
                    }

                }
                catch (PingException ex)
                {
                    MessageBox.Show("Failed!");

                }
                lblS1checking.Text = "Done.";
            }
    }