SignalR & SqlDependency Query performance

Deadly 提交于 2019-12-24 11:37:30

问题


I have a Table, it has around 1 million rows. This table is updated by web services, CMS applications and other sources. I want to Monitor few columns within this table. I read about SignalR and SqlDependency.

However it seems like SqlDependency will re-scan the entire table on every change?? My table is pretty large and I cant afford to rescan the DB upon every change.

is the only solution is to use Trigger or something? I really want to stay away from Triggers.

Here is the code:

public IEnumerable<JobInfo> GetData()
{

    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(
           @"SELECT [JobID],[Name],[LastExecutionDate],[Status]
           FROM [dbo].[JobInfo]", connection))
        {
            // Make sure the command object does not already have
            // a notification object associated with it.
            command.Notification = null;

            SqlDependency dependency = new SqlDependency(command);
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

            if (connection.State == ConnectionState.Closed)
                connection.Open();

            using (var reader = command.ExecuteReader())
                return reader.Cast<IDataRecord>()
                    .Select(x => new JobInfo(){ 
                        JobID = x.GetInt32(0), 
                        Name = x.GetString(1), 
                        LastExecutionDate = x.GetDateTime(2),  
                        Status  = x.GetString(3) }).ToList();                            



        }
    }        
}

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{            
    JobHub.Show(); 
}

Query in Example is...

SELECT [JobID],[Name],[LastExecutionDate],[Status]
FROM [dbo].[JobInfo]

Now imagine if this table has a million rows, it would really slow down the process.


回答1:


You could add in some criteria to your command query to filter such as -

SELECT [JobID],[Name],[LastExecutionDate],[Status]
FROM [dbo].[JobInfo]
WHERE [LastExecutionDate] > @lastExecutionDate

Then set the param using -

command.Parameters.Add(new SqlParameter("lastExecutionDate", SqlDbType.DateTime) { Value = DateTime.Now.ToUniversalTime() });

This way you will only receive notifications (for inserts/updates at least) where the LastExecutionDate field is later than the last time the SqlDependency was registered.



来源:https://stackoverflow.com/questions/32410204/signalr-sqldependency-query-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!