2014-09-16 3 views
0

나는 을 쓰고있다. SQL 서버 청취 연결 신청;데이터베이스에 연결을 청취하는 방법

시작 또는 처리 중에 언제든지 연결 케이블을 분리하거나 손상된 경우 연결이 가능할 때까지 APP가 잠자기 상태가됩니다. 연결이 복원되면 응용 프로그램이 활성화되어 SQL 명령 실행을 시작합니다.

SQL 연결을 수신하는 데 필요한 방법을 조언 해주십시오.

참고 : MessageQueue.Receive() 메카니즘과 유사한 청취 메커니즘을 이해해야한다고 생각합니다.

+0

[so]에 오신 것을 환영합니다. 일반적으로 SQL Server dB와 통신하고 나중에 연결을 닫으려면 트랜잭션 또는 트랜잭션 일괄 처리를 실행할 때만 연결을 엽니 다. 그래서'Connection.Open()'이 예외를 일으켰다면 당신은 잠들고 예외를 발생시키지 않을 때까지 주기적으로 연결을 ping 할 수 있습니다. 너가 알고 싶었던거야? –

+0

@Jeremy Thompson : 당신은 이미 말했습니다 : "Connection.Open()이 예외를 발생 시키면 잠자기 상태가되어 예외가 발생하지 않을 때까지 주기적으로 연결을 ping 할 수 있습니다."그러나 내 요구는 내 앱이 잠자기 상태가 될 것입니다. (CPU 자원을 소비하지 않음) 연결이 가능할 때까지 기다려야합니다 (네트워크 케이블이 플러그 또는 다른 이유입니다). 깨어나서 작동합니다. – GIANGPZO

+0

- 답장 5 개월 만에 꽤 예 .. SQL 서비스 시작 (이벤트 로그를 통해)을 통보하지 않으면 알림이 표시되지 않습니다. AFAIK는 유지하지 않는 한 방법이 없습니다. 핑/폴링. db 연결 가용성을위한 'FolderWatcher'라이브러리가 있다면 좋을 것입니다. 미안해. 하나도 몰라. –

답변

0

전체 구현을 작성하는 것이 복잡한 점입니다. 포인터를 줄 수 있습니다. 인터넷 연결을 사용할 수 있는지 여부를 모니터링하는 타이머가 필요합니다. 나는 당신의 필요에 따라 완전한 부분 논리를 작성했다. 개인 변수를 유지하여 연결 링크 연결/다시 연결을 모니터링해야 할 수도 있습니다.

public class Example 
{ 
    /// <summary> 
    /// External method for checking internet access: 
    /// </summary> 
    [DllImport("wininet.dll")] 
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue); 

    /// <summary> 
    /// C# callable method to check internet access 
    /// </summary> 
    public static bool IsConnectedToInternet() 
    { 
     int Description; 
     return InternetGetConnectedState(out Description, 0); 
    } 

    private static Timer aTimer; 

    /// <summary> 
    /// Fired when a connection is made to the server 
    /// </summary> 
    public event EventHandler ConnectedToNetwork; 

    public void OnConnected() 
    { 
     try 
     { 
      if (null != ConnectedToNetwork) 
      { 
       ConnectedToNetwork(this, new EventArgs()); 
      } 
     } 
     catch (Exception ex) 
     { 

     } 
    } 

    /// <summary> 
    /// Fired when loses its connection to the server 
    /// </summary> 
    public event EventHandler DisconnectedFromNetwork; 


    /// <summary> 
    /// Clears server notifications 
    /// </summary> 
    public void OnDisconnected() 
    { 
     try 
     { 

      if (null != DisconnectedFromNetwork) 
      { 
       DisconnectedFromNetwork(this, new EventArgs()); 
      } 
     } 
     catch (Exception ex) 
     { 

     } 
    } 


    public void Intialize() 
    { 
     // Create a timer with a two second interval. 
     aTimer = new System.Timers.Timer(2000); //Timer will start when your application is started 
     // Hook up the Elapsed event for the timer. 
     aTimer.Elapsed += OnTimedEvent; 
     aTimer.Enabled = true; 

     Console.WriteLine("Press the Enter key to exit the program... "); 
     Console.ReadLine(); 
     Console.WriteLine("Terminating the application..."); 
    } 
    private void OnTimedEvent(Object source, ElapsedEventArgs e) 
    { 
     if (IsConnectedToInternet()) 
     { 
      OnConnected(); 
      //Code to APP will wake up and execute SQL commands. 
     } 
     else 
     { 
      OnDisconnected(); 
     } 
    } 
} 

// DBClass 'ClientCodeSubscription' should verify whetehr the DB is up and running. 
class DBClass 
{ 
    public bool DBServerIsRunning { get; set; } 
    //In DB area 
    private void ClientCodeSubscription() 
    { 
     if (DBServerIsRunning) //Check to see if DB service is running. 
     { 
      Example ex = new Example(); 
      ex.ConnectedToNetwork += Example_ConnectedToNetwork; //this is your client code probably in    this case the DB 
     } 

    } 

    static void Example_ConnectedToNetwork(object sender, EventArgs e) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

이것은 좋지만 DB Watcher가 DB와 동일한 상자에 없다는 가정하에 가정합니다. 모뎀/LAN 활성 신호는 SQL Server 가동 시간과 다릅니다. @Alex, Jeremy Thompson 그리고 Srikanth 제안은 효과가 있지만 사용하는 방법에 따라 다릅니다. 이 APP는 모니터링 도구입니까? (다시 알림이 끝날 때까지 잠자기 상태가 된 후)? 또는 그것은 DB에 대한 작가 일뿐입니다. 나는 개인적으로 DB에 간단한 작가가 있다면 제레미의 제안쪽으로 기울다. –

+0

게시자/구독자 메커니즘에 대한 답변이 업데이트되었습니다. Connection이 사용 가능하게되면 가입 한 모든 클라이언트 (Here DB)에게 통보됩니다. – Srikanth

+0

답변 해 주셔서 감사합니다! 하지만 APP가 좋지 않기 때문에 타이머 나 while 루프를 사용할 필요가 없습니다. 나는 모니터 메카니즘을 사용해야한다고 생각하지만, 매우 어렵다고 생각합니다. 아이디어가 있으면 저에게 말하십시오. 미리 감사드립니다! – GIANGPZO

관련 문제