简体   繁体   中英

How to detect Database Changes with SqlDependency and c#

I want to fire a Method each Time a database detected a change. I tried this in a Console Application: (ServiceBroker in Database is active)

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlDependencyExample
{
    class Program
    {
        static void Main(string[] args)
        {
            
            string connectionString = "xxx";
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();

            using (SqlCommand command = new SqlCommand(
            "SELECT [ID], [Name] FROM [dbo].[Users]", connection))
            {
                SqlDependency dependency = new SqlDependency(command);
   
                SqlDependency.Start(connectionString);
                
                dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
                
                using (SqlDataReader reader = command.ExecuteReader())
                {                   
                    while (reader.Read())
                    {
                        Console.WriteLine("ID: {0}, Name: {1}", reader.GetInt32(0), reader.GetString(1));
                    }
                }
            }
        }
        private static void OnDependencyChange(object sender, SqlNotificationEventArgs e)
        {
            
            Console.WriteLine("Database change detected.");
            //Fire something
        }
    }
}

But the Problem is, the application starts, and instantly writes "Database change detected." and closed and when I´m adding a row in my Database, it is not handling "OnDependencyChange"... The Console is writing every row which exists. So the Connection is working, but it detects no new rows in the Database

There is nothing that prevents the program to stop, after it executes once. You can add the Console.ReadLine() statement before the closing bracket of the Main function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM