如何解决SignalR SqlDependancy OnChange事件未触发
我将SignalR与MVC一起使用,并在sqlDependency的Change Event上创建。但是当我在数据库中更新时它不会触发。当我在Db中执行查询“ ALTER DATABASE MyDatabase SET ENABLE_broKER”
我在NotificationComponent中写过
public void RegisterNotification(DateTime currentTime)
{
string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
string sqlCommand = @"SELECT * from [dbo].[Event] where UpdatedTime > @UpdatedTime";
sqlDependency.Start(conStr);
using (sqlConnection con = new sqlConnection(conStr))
{
if (con.State != System.Data.ConnectionState.Open)
{
con.open();
}
sqlCommand cmd = new sqlCommand(sqlCommand,con);
cmd.Parameters.AddWithValue("@UpdatedTime",currentTime);
cmd.Notification = null;
sqlDependency sqlDep = new sqlDependency(cmd);
//sqlDep.OnChange += new OnChangeEventHandler(sqlDep_OnChange);
sqlDep.OnChange += sqlDep_OnChange;
//we must have to execute the command here
cmd.ExecuteReader().dispose();
//using (sqlDataReader reader = cmd.ExecuteReader())
//{
// // nothing need to add here Now
//}
}
}
public void sqlDep_OnChange(object sender,sqlNotificationEventArgs e)
{
if (e.Type == sqlNotificationType.Change)
{
sqlDependency sqlDep = sender as sqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
//from here we will send notification message to client
var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
notificationHub.Clients.All.notify("added");
//re-register notification
RegisterNotification(DateTime.Now);
}
}
public List<Event> GetEvents(DateTime afterDate)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
return dc.Events.Where(a => a.UpdatedTime > afterDate).OrderByDescending(a => a.UpdatedTime).ToList();
}
}
在JS中
var notificationHub = $.connection.notificationHub;
$.connection.hub.start().done(function () {
console.log('Notification hub started');
});
notificationHub.client.notify = function (message) {
if (message && message.toLowerCase() == "added") {
updateNotificationCount();
}
}
在Startup.cs配置功能中:
app.MapSignalR();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。