带有signalR的SqlDependency没有一致地触发dependency_OnChange

时间:2016-09-21 20:26:56

标签: asp.net sql-server iis signalr c#-2.0

设置

•Visual Studio 2010

•IIS 8.5

•.NET Framework 4.6

•Microsoft SQL Server 2014

•IIS上的AppPool帐户是域\ web

我有一个监控数据库表中更改的网页。我使用dependency_OnChange监视数据库并通过signalR将数据传递给用户。我在dependency_OnChange方法中设置了一个断点,它只在数千次数据库更新中被点击几次。

在web.config中......我正在使用Integrated Security = True。

我的用户是sql框上的系统管理员。 (这只是为了证明概念)

在Global.asax中...指定一个队列名并停止并启动sqldependency

void Application_Start(object sender, EventArgs e)
{
    var queuename = "Q_Name";
    var sConn = ConfigurationManager.ConnectionStrings["singalR_ConnString"].ConnectionString;
    SqlDependency.Stop(sConn, queuename);
    SqlDependency.Start(sConn, queuename);
}

void Application_End(object sender, EventArgs e)
{  
    var queuename = "Q_Name";
    var sConn = ConfigurationManager.ConnectionStrings["singalR_ConnString"].ConnectionString;
    SqlDependency.Stop(sConn, queuename);
}

在代码背后......

public void SendNotifications()
{
    //Identify Current User and Row No
    string CurrentUser = GetNTName();


    string message = string.Empty;
    string conStr = ConfigurationManager.ConnectionStrings["singalR_ConnString"].ConnectionString;

    using (SqlConnection connection = new SqlConnection(conStr))
    {
        string query = "SELECT [RowNo] FROM [dbo].[Test] WHERE [User] =  @User";
        string SERVICE_NAME = "Serv_Name";

        using (SqlCommand command = new SqlCommand(query, connection))
        {
            // Add parameters and set values.
            command.Parameters.Add("@User", SqlDbType.VarChar).Value = CurrentUser;
            //Need to clear notification object
            command.Notification = null;
            //Create new instance of sql dependency eventlistener (re-register for change events)
            SqlDependency dependency = new SqlDependency(command, "Service=" + SERVICE_NAME + ";", 0);
            //SqlDependency dependency = new SqlDependency(command);
            //Attach the change event handler which is responsible for calling the same SendNotifications() method once a change occurs.
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();
                message = reader[0].ToString();
            }
        }
    }
    //If query returns rows, read the first result and pass that to hub method - NotifyAllClients.
    NotificationsHub nHub = new NotificationsHub();
    nHub.NotifyAllClients(message);
}


private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{            
    //Check type to make sure a data change is occurring
    if (e.Type == SqlNotificationType.Change)
    {
        // Re-register for query notification SqlDependency Change events.
        SendNotifications();
    }
}

NotificationsHub.cs页面......

    //Create the Hub
    //To create a Hub, create a class that derives from Microsoft.Aspnet.Signalr.Hub. 

//Alias that can call class from javascript. - i.e.  var hub = con.createHubProxy('DisplayMessage');
[HubName("DisplayMessage")]
public class NotificationsHub : Hub //Adding [:Hub] let c# know that this is a Hub 
{
    //In this example, a connected client can call the NotifyAllClients method, and when it does, the data received is broadcasted to all connected clients.

    //Create NotifyAllClients Method
    //public means accessible to other classes
    //void means its not returning any data
    public void NotifyAllClients(string msg)
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
        //When this method gets called, every single client has a function displayNotification() that is going to be executed
        //msg is the data that is going to be displayed to all clients.
        context.Clients.All.displayNotification(msg);                                                       
    }

}

1 个答案:

答案 0 :(得分:0)

我在这里要做的第一件事是将Sql Dependency设置重构为一个独立的方法,并从你的发送通知中调用它。 (SoC和DRY)因为如果你在其他地方创建其他SqlDependencies,他们会互相绊倒。其次,您正在创建一个新的NotificationsHub,您应该获得当前活动的中心。

DefaultHubManager hubManager = new DefaultHubManager();
hub = hubManager.ResolveHub("NotificationsHub");
hub.NotifyAllClients(message);

还有一种较旧的方式来获取集线器,但我不确定它是否仍然有效

GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>()

我在这个答案中也有一个更简单版本的例子。 Polling for database changes: SqlDependency, SignalR is Good

如果您有任何问题,请与我们联系。