2016-05-31 4 views
1

내 측면에있는 클라이언트 측에 알림을 보내려면 signalR을 사용하여 서버 쪽 인트라넷 응용 프로그램이 포함 된 알림 시스템을 개발하고 있습니다 Windows 데스크톱 C# 응용 프로그램.내 Windows 바탕 화면을 만드는 방법 C#을 응용 프로그램이 연결을 잃어버린 경우에 서버에 다시 연결

두 응용 프로그램은 SignalR 및 .NET Framework 4.5.2를 사용하여 구현 된 C# 응용 프로그램입니다.

현재 내 응용 프로그램을 서버에 연결하여 알림을 수신하도록 설정합니다. Windows 데스크톱 응용 프로그램의 시작 부분에 구현되었습니다.

내 응용 프로그램 (Windows 데스크톱 응용 프로그램)이 데스크톱 응용 프로그램이 이미 실행 중일 때 연결이 끊어진 경우에 대비하여 서버에 연결하려고합니다.

은 인트라넷 응용 프로그램에 내 응용 프로그램을 연결 여기 내 C# 코드 아래

public static HubConnection connection; 
static void Main() 
{ 
    IHubProxy _hub; 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 


    string urlToConnectIntoIntranetServer = @"http://localhost:46412"; 
    connection = new HubConnection(url); 
    connection.Headers.Add("Securitytoken", "87654321"); 
    _hub = connection.CreateHubProxy("NotificationHub"); 
    _hub.On("broadcastMessage", x => reateToastNotification.CreateToast(x)); 

    connection.Closed += connection_Closed; 
    connection.Start().Wait(); 
    Application.Run(new Form1()); 
    CreateToastNotification.CreateToast("Hellow world"); 
} 

    static void connection_Closed() 
     { 
      Pooling(10); 
     } 
    private static void Pooling(int i) 
     { 
      int nTimes = i; 
      if (nTimes == 0) 
       return; 

      try 
      { 
       if (connection!=null) 
       connection.Start().Wait(); 

      } 
      catch (AggregateException ae) 
      { 
       Thread.Sleep(1000); 
       Pooling(nTimes - 1); 
      } 
     } 
+0

연결이 닫힌 이벤트를 잡아라. 닫혀 있고 다시 연결하려면 처리기에서 다시 연결하십시오. 예를 들어 당신 때문에 폐쇄되었습니다. 응용 프로그램을 종료하면 종료됩니다. –

+0

메모에서 코드 서식을 지정하는 데 문제가 있습니다. 더 읽기 쉽도록 코드를 수정하는 것이 좋습니다. –

+0

감사합니다. Ben, 코드를 더 읽기 좋게 만들려는 귀하의 제안을 알고 싶습니다. – Laila

답변

0

당신은 그것은 어쩌면 단지 아이디어와이다 (이런 식으로 뭔가를 시도 할 수 있음을 구현하는 가장 좋은 방법은 무엇입니까 작은 못생긴 ^^) :

 private void Connection_StateChanged(StateChange obj) 
     { 
      //when the connection is Disconnected 
      if (obj.NewState == ConnectionState.Disconnected) 
      { 
       var current = DateTime.Now.TimeOfDay; 
       // start a timer after 30 secs and retry every 15secs 
       SetTimer(current.Add(TimeSpan.FromSeconds(30)), TimeSpan.FromSeconds(15), StartCon); 
      } else { 
       if(_timer!=null) 
        _timer.Dispose(); 
      } 
     } 

     private async Task StartCon() 
     { 
      await Connection.Start(); 
     } 

     private Timer _timer ; 
     private void SetTimer(TimeSpan starTime, TimeSpan every, Func<Task> action) 
     { 
      var current = DateTime.Now; 
      var timeToGo = starTime - current.TimeOfDay; 
      if (timeToGo < TimeSpan.Zero) 
      { 
       return; 
      } 
      _timer = new Timer(x => 
      { 
       action.Invoke(); 
      }, null, timeToGo, every); 
     }