2016-05-31 9 views
1

私は、クライアント側に通知を送信するためにsignalRを使用してサーバー側のイントラネットアプリケーションを含む通知システムを開発していますWindowsデスクトップC#アプリケーション。どのように私のWindowsデスクトップのC#アプリケーションを再接続する場合は、接続が失われた場合にサーバーに再接続

両方のアプリケーションは、SignalRと.NETフレームワーク4.5.2を使用して実装されたC#アプリケーションです。

現在、私は自分のアプリケーションをサーバーに接続して通知を受け取るようにしています。これはWindowsデスクトップアプリケーションの開始時に実装されています。

私のアプリケーション(Windowsデスクトップアプリケーション)は、デスクトップアプリケーションが既に実行されている間に何らかの理由で接続が失われた場合に備えて、サーバーに接続しようとします。あなたは(それが唯一のアイデアだ。このような何かを試してみて、多分できるイントラネット・アプリケーション

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

に私のアプリを接続して、私のC#のコードダウンここ

ことを実施するための最良の方法は何か

少し醜い^^):

 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); 
     } 
関連する問題