2015-07-28 20 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