SignalR击中数据库两次

本文关键字:两次 数据库 SignalR | 更新日期: 2023-09-27 18:05:18

数据库表(DummyData)只有一列(Message)和一条值为"hello"的记录/行。我使用signalR在网页上显示此值。每当在DB中更新此值时,网页上的文本也会更新而不刷新。

我看到的问题是,应用程序击中数据库两次。这是故意的还是错误的代码?(这一页只打开一次。没有其他实例)

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);
   }
 }

下面是调试时如何命中断点的:

  • on page load:

    1. OnConnected ()
    2. NotifyAllClients ()
    3. SendNotifications ()
    4. NotifyAllClients() //why is this hit again
    5. SendNotifications ()
  • 当我运行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 ()

SignalR击中数据库两次

至少对于初始页面加载,我是这样假设的:

OnConnected的客户端连接上调用NotifyAllClients,然后在客户端的done函数中又调用了NotifyAllClients