Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep sql dependency doing the its purpose

I have a console application.

I wanna keep watching the changes on a specific column in my database table.

I read through internet and I have found that sql dependency is good for my purpose. I started learning about it and I did the following:

  1. create a class.
  2. In the constructor, I called the static function start and I called a function that has all the sql dependency settings.

My problem

When I run the application using the start click on visual studio 2013, the apps works and then stops. However, what I need is that the apps starts working and keep watching for changes in my database's table.

Could you help me please?

Code:

This is a very very simple c# code.

public class MyListener
    {
        public MyListener()
        {
            SqlDependency.Start(getConnectionString());
            this.listen();
        }

        private string getConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["popup"].ConnectionString.ToString();
        }
        private void listen()
        {
            string query = "SELECT CallerID FROM TransferToSIP WHERE hasBeenRead = 0";
            SqlConnection con = new SqlConnection(getConnectionString());
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            using (cmd)
            {
                SqlDependency dependency = new SqlDependency(cmd);
                dependency.OnChange += new
                   OnChangeEventHandler(OnDependencyChange);
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                }
            }
        }
        void OnDependencyChange(object sender, SqlNotificationEventArgs e)
        {
            Console.WriteLine("Roma");
        }
        void Termination()
        {
            SqlDependency.Stop(getConnectionString());
            Console.Read();
        }
like image 837
Marco Dinatsoli Avatar asked Jul 04 '26 11:07

Marco Dinatsoli


1 Answers

The problem is in absence of the resubscruption. You should call the listen method inside of OnDependencyChange. I know that it is weird, but it is the SqlDependency class.

like image 131
dyatchenko Avatar answered Jul 07 '26 01:07

dyatchenko