使用SQLDependency
和SignalR Hub时出现问题。启动与集线器的连接后,即使数据库中没有任何更改,SQLDependency
的OnChange
事件也始终会触发。
这是我的包含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
,则由于某种原因(除了更改数据外)调用了处理程序。订阅本身可能失败。