2015-07-28 64 views
0

數據庫表(DummyData)具有單列(Message)並且只有一個記錄/行的值爲「hello」。我使用signalR在網頁上顯示此值。只要此值在數據庫中更新,網頁上的文本也會更新而不刷新。所有這些工作正常。SignalR正在擊中數據庫兩次

我看到的問題是,該應用程序擊中數據庫兩次。這是由設計還是錯誤的代碼。 (頁面被打開一次。沒有任何其他情況下)

ASPX

<script> 
     $(function() { 
      var notify = $.connection.notificationsHub; 

      $.connection.hub.start().done(function() { 
       notify.server.notifyAllClients(); 
      }); 

      notify.client.displayNotification = function (msg) {    
       $("#newData").html(msg);        
      };    
     }); 
    </script> 
    <span id="newData"></span> 

aspx.cs

public string SendNotifications() 
     { 
      using (SqlConnection connection = new SqlConnection(conStr)) 
      { 
       string query = "SELECT [Message] FROM [dbo].[DummyData]"; 
       SqlCommand command = new SqlCommand(query, connection) 
        command.Notification = null; 
        SqlDependency dependency = new SqlDependency(command); 
        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); 
        connection.Open(); 
        SqlDataReader reader = command.ExecuteReader(); 

        if (reader.HasRows) 
        { 
         reader.Read(); 
         message = reader[0].ToString(); 
        }      
      } 
      return message; 
     } 

     private void dependency_OnChange(object sender, SqlNotificationEventArgs e) 
     { 
      if (e.Type == SqlNotificationType.Change) 
      { 
       NotificationsHub obj = new NotificationsHub(); 
       obj.NotifyAllClients();     
      }    
     } 

NotificationsHub.cs

public class NotificationsHub : Hub 
{ 
    Messages obj = new Messages(); 
    public void NotifyAllClients() 
    { 
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>(); 
    context.Clients.All.displayNotification(obj.SendNotifications()); 
    } 

    public override Task OnConnected() 
    { 
    NotifyAllClients(); 
    return base.OnConnected(); 
    } 
    public override Task OnDisconnected(bool stopCalled) 
    { 
    NotifyAllClients(); 
    return base.OnDisconnected(stopCalled); 
    } 
} 

這裏是斷點如何打在調試:

  • 在頁面加載:

    1. OnConnected()
    2. NotifyAllClients()
    3. SendNotifications()
    4. NotifyAllClients() //why is this hit again
    5. Send通知()
  • 當我運行update DummyData Set Message='helloworld'

    1. dependency_OnChange()
    2. NotifyAllClients()
    3. SendNotifications()
    4. dependency_OnChange()//hit a second time here too
    5. NotifyAllClients()
    6. SendNotifications()

回答

3

至少在初始頁面加載我假設這:

你在在OnConnected客戶端連接呼叫NotifyAllClients,然後在客戶端的done功能有到NotifyAllClients另一個電話。

+0

請問能否請教,如何防止第二次打 – Qwerty

+0

留下兩個電話中的哪一個,其實並不重要。 – rdoubleui