2015-01-05 6 views
1

나는 겉으로보기에는 간단한 작업을 수행하려고하지만 단지 내 프로그램을 작동시키지 못합니다.프로그램을 멈추지 않고 반복하십시오?

이것은 C#이며, 내 서버에 ping을 보내고 응답하는 경우 응답을 보냅니다. 내가 겪고있는 문제는 다시 시도하기 전에 X 초 동안 기다려서 서버에 핑 플러드가 발생하지 않도록하려는 것입니다. 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. 

     } 
+1

사용 배경 작업자 –

+1

를 사용하여 모든 x 초 –

+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."; 
      } 
    } 
+1

스레드 처리를 필요로하지 않는 멋진 솔루션 – Liath

+0

이것은 UI를 최대 2 개까지 고정시킬 것입니다 (C# 5에서 새로운 작업 비동기 항목 사용). sec (ping timeout의 경우)마다 '30 초'로 설정합니다. 해결 방법은 이벤트 핸들러를'Task.Run (() => {...});'으로 호출하고 UI 호출을 호출하는 것입니다 (winforms처럼 보이므로 예를 들어'this.BeginInvoke (new Action (() => lblS1Check.Text = "DOWN"));))') – Sinatr

+0

이제는 효과가 있다고 생각합니다. 대단히 감사합니다! – Mohamed

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); 
      } 
     } 
    } 
} 
관련 문제