SqlDependency.OnChange dependency_OnChange没有触发

时间:2017-04-05 08:35:10

标签: c# signalr

我刚刚开始使用SignalR并根据不同文章和多个问题设置配置。我已经完成了每一步。我无法弄清楚为什么依赖OnChange没有被解雇?

[HubName("broadcastHub")]
public class BroadcastHub : Hub
{  
    [HubMethodName("sendNotifications")]
    public Task<object> SendNotifications()
    {
        DataTable dt = new DataTable();
        using (var connection = new SqlConnection(strConnectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                command.Notification = null;
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                var reader = command.ExecuteReader();
                dt.Load(reader);
                connection.Close();

            }
        }
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<BroadcastHub>();
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
        return (context.Clients.All.RecieveNotification(json));
    }
    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            SendNotifications();
        }
    }
}

它第一次正常工作,我得到了预期的数据。但是当在表中进行任何更改时,它不会触发dependency_OnChange

我还发现使用以下查询启用了Broker Service: -

select is_broker_enabled from sys.databases where name='msdb' 
select is_broker_enabled from sys.databases where name='mydb'

两者都是enabled,值为1

我在SendNotifications中使用的查询是: -

select Id,OXEName,OXEIP IP,ConnectionStatus Status, Case WHEN ConnectedOxeIP IS NULL OR ConnectedOxeIP = '' THEN OXEIP ELSE ConnectedOxeIP END as ConnectedOxeIP from PBXDetail

Java脚本

$(function () {
    var notifications = $.connection.broadcastHub;
    notifications.client.recieveNotification = function (response) {
    };
    $.connection.hub.start().done(function () {
        notifications.server.sendNotifications();
    }).fail(function (e) {
    });             
});

Startup.cs

[assembly: OwinStartup(typeof(myNameSpace.Startup))]
namespace myNameSpace
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR(new HubConfiguration() { EnableJSONP = true });
        }
    }
}

Global.asax中

protected void Application_Start(object sender, EventArgs e)
{
   System.Data.SqlClient.SqlDependency.Start(strConnectionString);
}

protected void Application_End(object sender, EventArgs e)
{
   System.Data.SqlClient.SqlDependency.Stop(strConnectionString);
}

1 个答案:

答案 0 :(得分:1)

我已经想出来并将其作为答案发布,以便任何将面临此类问题的未来读者都能够弄明白。

我调试了一段代码,发现我在SqlNotificationEventArgs的{​​{1}}处获得了带有值的参数,其中包括:

dependency_OnChange

如果信息无效,请告诉我我的查询存在问题。然后我改变了我的查询语法,如下所示,它工作正常。

Info => Invalid
Type => Subscribe
Source => Statement

以下是我找到的查询状态:

select [Id],[OXEName],[OXEIP] as [IP],[ConnectionStatus] as [Status], Case WHEN [ConnectedOxeIP] IS NULL OR [ConnectedOxeIP] = '' THEN [OXEIP] ELSE [ConnectedOxeIP] END as [ConnectedOxeIP] from dbo.PBXDetail

执行此操作后,我发现在每个页面刷新dependency_OnChange都会触发刷新页面的次数。例如,如果页面刷新10次,它将触发10次。所以我做了以下更改:

select * from table // did not work
select ID from table // did not work
select [ID] from table // did not work
select [ID] from dbo.table // Worked

<强>的ServiceController

[HubMethodName("sendNotifications")]
public Task<object> SendNotifications()
{
    DataTable dt = new DataTable();
    using (var connection = new SqlConnection(strConnectionString))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            command.Notification = null;
            if (ServiceController.dependency == null)
            {
                ServiceController.dependency = new SqlDependency(command);
                ServiceController.dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
            }
            var reader = command.ExecuteReader();
            dt.Load(reader);
            connection.Close();
        }
    }
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<BroadcastHub>();
    var json = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
    return (context.Clients.All.RecieveNotification(json));
}

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
    if (e.Type == SqlNotificationType.Change)
    {
        if (ServiceController.dependency != null)
        {
            ServiceController.dependency.OnChange -= dependency_OnChange;
            ServiceController.dependency = null;
        }
        SendNotifications();
    }
}

<强> Global.asax中

 public static class ServiceController
 {
    internal static SqlCommand command = null;
    internal static SqlDependency dependency = null;
    internal static bool isCachingEnabled = false;
 }