使用SQLDependency和SignalR Hub时出现问题。启动与集线器的连接后,即使数据库中没有任何更改,SQLDependencyOnChange事件也始终会触发。

这是我的包含SQLDependency的代码

public List<NotifCenterModel> countNewTransaksi()
{
    List<NotifCenterModel> ncms = new List<NotifCenterModel>();
    command = new SqlCommand(@"SELECT Edolpuz_DB.dbo.TABEL_NOTIF_CENTER.NAMA_TABEL,Edolpuz_DB.dbo.TABEL_NOTIF_CENTER.JUMLAH_NOTIF FROM Edolpuz_DB.dbo.TABEL_NOTIF_CENTER",connect);
    try
    {
        command.Notification = null;
        SqlDependency dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
        if(connect.State == ConnectionState.Open)
            connect.Close();
        connect.Open();
        reader = command.ExecuteReader();
        while (reader.Read())
        {
            ncms.Add(new NotifCenterModel(reader[0].ToString(), int.Parse(reader[1].ToString())));
        }
        return ncms;
    }
    catch { return null; }
    finally { connect.Close(); }
}

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
    TransHub.Show();
}

在我的集线器中,代码是这样的

public class TransHub : Hub
{
    public static void Show()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TransHub>();
        context.Clients.All.displayStatus();
    }
}

这是我的javascript

 $(function () {
            // Proxy created on the fly
            var job = $.connection.transHub;
            // Declare a function on the job hub so the server can invoke it
            job.client.displayStatus = function () {
                //     alert("test");
                getData();
            };

            // Start the connection
            $.connection.hub.start().done(function () {
                getData();
            }).fail(function (e) {
                alert(e);
            });

        });

function getData() {
    $.ajax({
        url: server + '/Admin/GetNotifikasi/',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            for (var i = 0; i < data.length ; i++)
            {
                if (data[i].nama_tabel == "TABEL_TRANSAKSI")
                {
                    $('#notifTrans').text(data[i].jumlah_notif);
                }
                else if (data[i].nama_tabel == "TABEL_KONF_BAYAR")
                {
                    $('#notifBayar').text(data[i].jumlah_notif);
                }
                else if (data[i].nama_tabel == "TABEL_TESTI")
                {
                    $('#notifTesti').text(data[i].jumlah_notif);
                }
                else if (data[i].nama_tabel == "TABEL_KUSTOM_ORDER")
                {
                    $('#notifKustom').text(data[i].jumlah_notif);
                }
            }
        }
    });
}

connection.hub.start().done中调用getData()时,它将不断触发并产生无限循环,但是当我不调用getData()时,当表中的数据更改时不会触发该事件。如何解决?

最佳答案

dependency_OnChange中,您需要检查e.Type。如果是!= SqlNotificationType.Change,则由于某种原因(除了更改数据外)调用了处理程序。订阅本身可能失败。

09-25 17:13
查看更多