SqlDependency OnChangeEventHandler не запускается при изменении запроса в SqlCommand - PullRequest
0 голосов
/ 16 мая 2019

Я написал код, используя SqlDependency.При использовании оператора выбора со списком столбцов вызывается событие OnChangeEventHandler, но когда я изменяю оператор выбора для получения количества строк, событие OnChangeEventHandler не срабатывает.

Код, в котором запускается событие OnChangeEventHandler:

открытый статический класс Notification {static readonly string connString = @ "source data = DESKTOP-591MN5Q \ SQLEXPRESS01; начальный каталог = новый; встроенная защита = True;";внутренняя статическая команда SqlCommand = null;внутренняя статическая зависимость SqlDependency = null;

    public static int GetNotificationCount()
    {
        try
        {               
            var messages = new List<tblNotification>(); 
            using (var connection = new SqlConnection(connString))
            {
                connection.Open();
                using (command = new SqlCommand(@"SELECT  [NotificationId],[UserId],[IsSeen],[Message],[CreatedDate],[ActionID] FROM [dbo].[tblNotification]", connection))
                {
                    command.Notification = null;

                    if (dependency == null)
                    {
                        dependency = new SqlDependency(command);
                        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    }

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

                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        messages.Add(item: new tblNotification
                        {
                            NotificationId = (int)reader["NotificationId"],
                            UserId = reader["UserId"] != DBNull.Value ? (string)reader["UserId"] : "",
                            IsSeen = reader["IsSeen"] != DBNull.Value ? (string)reader["IsSeen"] : "",
                            Message = reader["Message"] != DBNull.Value ? (string)reader["Message"] : "",
                            CreatedDate = reader["CreatedDate"] != DBNull.Value ? (string)reader["CreatedDate"] : "",
                            ActionID = reader["ActionID"] != DBNull.Value ? (string)reader["ActionID"] : "",
                        });
                    }
                }
            }
            return messages.Count;
        }
        catch (Exception ex)
        {

            return 0;
        }
    }

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

Код, в котором не запускается событие OnChangeEventHandler:

открытый статический класс Уведомление {статическая строка только для чтения connString = @ "source data = DESKTOP-591MN5Q \SQLEXPRESS01; исходный каталог = новый; встроенная защита = True; ";внутренняя статическая команда SqlCommand = null;внутренняя статическая SqlDependency dependency = null;

public static int GetNotificationCount()
{
    try
    { 
        int notificationCt;
        using (var connection = new SqlConnection(connString))
        {
            connection.Open();
            using (command = new SqlCommand(@"SELECT  COUNT([NotificationId]) as NotificationCount FROM [dbo].[tblNotification]", connection))
            {
                command.Notification = null;

                if (dependency == null)
                {
                    dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                }

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

                notificationCt = Convert.ToInt32(command.ExecuteScalar()); 
            }
        }
        return notificationCt;
    }
    catch (Exception ex)
    {

        return 0;
    }
}

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

}

Исключений не возникает.На что я обратил внимание, это когда

использует (command = new SqlCommand (@ "SELECT [NotificationId], [UserId], [IsSeen], [Message], [CreatedDate], [ActionID] FROM [dbo]).[tblNotification] ", connection))

, во время выполнения функции GetNotificationCount () отладчик не переходит к событию dependency_OnChange.Но когда

с использованием (command = new SqlCommand (@ "SELECT COUNT ([NotificationId]) в качестве NotificationCount FROM [dbo]. [TblNotification]", connection))

существует, отладчик перемещаетсямежду GetNotificationCount () и dependency_OnChange ().

Поэтому, когда я добавляю новую запись в таблицу sql, dependency_OnChange () не срабатывает.

...