【问题标题】:signalr with sqldepdency firing multiple times for each browser instance为每个浏览器实例多次触发 sqldepdency 的信号器
【发布时间】:2016-08-17 21:21:29
【问题描述】:

我有一个带有 vs2013 和 .net 框架 4.5.1 的 asp.net mvc 应用程序,它应该在某个字段更新和某个记录 ID 时通知用户。 当我打开一个浏览器实例时一切正常,但是当我在同一台机器或不同机器上打开另一个选项卡或浏览器时,它会多次触发 sqldepdencychange 事件。

以下是我的中心代码

public class MessagesHub : Hub
    {
        private static string conString = ConfigurationManager.ConnectionStrings["FleetLink_DB"].ToString();

        private static string hostName = "";


        public static void SendMessages(string hName)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
            hostName = hName;
            context.Clients.Group(hostName).updateMessages(hName);
        }

        public Task leaveGroup(string hName)
        {
            return Groups.Remove(Context.ConnectionId, hName);
        }

        public Task joinGroup(string hName)
        {
            return Groups.Add(Context.ConnectionId, hName);
        }
}

下面是我的信号器脚本文件

  $(function () {
            var dialog, form
            // Declare a proxy to reference the hub.

            var notifications = $.connection.messagesHub;
            //debugger;
            //Create a function that the hub can call to broadcast messages.
            notifications.client.updateMessages = function (hName) {
                alert("testing");
                getoneMessages(hName)
            };

            $.connection.hub.logging = true;
            $.connection.hub.start().done(function () {
                var hostName = getUrlVars()["System_Name"];
                notifications.server.joinGroup(hostName);
            }).fail(function (e) {
                alert(e);
            });
        });

        function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

        function getoneMessages(hName) {
            var tbl = $('#selectable');
            //alert('mesgID=' + mesgID)
            //var tbl = $('#selectable');
            $.ajax({
                url: '/controller/view',
                cache: false,
                contentType: 'application/html ; charset:utf-8',
                type: 'GET',
                dataType: 'html'
            }).success(function (result) {
                //alert(result);
                tbl.empty().append(result);
            }).error(function (exception) {
                //alert('failed= ' + exception);
            });
        }

        window.onbeforeunload = function (e) {
            var hostName = getUrlVars()["System_Name"];
            notifications.server.joinGroup(hostName);
            $.connection.hub.stop();

        };

下面是我的部分视图代码以及 RegisterForNotification 和 depdendency_onchange 事件的定义

public PartialViewResult SignalRTesterPartialView()
{
 /...COde not included for brevity..../
   RegisterForNotifications(ID);
}



public void RegisterForNotifications(int mID)
        {
            var efConnectionString = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            var builder = new EntityConnectionStringBuilder(efConnectionString);
            var regularConnectionString = builder.ProviderConnectionString;

            string commandText = null;


            commandText = "select ID,Status,Name from tblABC where ID=" + strID;

                using (SqlConnection connection = new SqlConnection(regularConnectionString))
                {
                    using (SqlCommand command = new SqlCommand(commandText, connection))
                    {
                        connection.Open();

                        var dependency = new SqlDependency(command);
                        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                        // NOTE: You have to execute the command, or the notification will never fire.
                        var reader = command.ExecuteReader();
                    }
                }

        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change && e.Info== SqlNotificationInfo.Update)
            {
                MessagesHub.SendMessages(hName);
            }

            RegisterForNotifications(1012);


        }

不确定为什么我打开的每个其他浏览器实例都会多次触发发送消息。任何指针都会有所帮助!

【问题讨论】:

    标签: asp.net-mvc-4 signalr sqldependency


    【解决方案1】:

    完成后删除EventHandler

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change && e.Info== SqlNotificationInfo.Update)
        {
            MessagesHub.SendMessages(hName);
        }
    
        //remove event handler
        SqlDependency dependency = sender as SqlDependency;
        dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange);
    
        RegisterForNotifications(1012);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2022-10-04
      • 2015-11-15
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多