0

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

2
  • Make sure that the Service Broker is enabled for the database Commented Jan 4, 2023 at 15:10
  • It is enabled.. Commented Jan 5, 2023 at 5:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I´ve added Console.ReadLine(). Now i've started it again, let it run, added a row in the database but nothing happend? Its again not handling the OnChange Event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.