SQLDependency OnChange事件产生无限循环

时间:2015-02-03 03:27:41

标签: javascript c# asp.net-mvc-4 signalr-hub sqldependency

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

以下是我的代码,其中包含OnChange

SQLDependency

在我的Hub中代码就像这样

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

这是我的javascript

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

当我在 $(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()时,它不会触发表中数据更改时的事件。如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

根据此网站(https://docs.microsoft.com/en-us/previous-versions/aewzkxxh(v=vs.90)),查询中的表名称必须是两部分名称,例如[dbo]。[TABEL_NOTIF_CENTER]。

  

必须明确声明SELECT语句中的预计列,并且表名必须由两部分组成。请注意,这意味着该语句中引用的所有表必须位于同一数据库中。

[]的

相关问题