如何保持sql依存关系的目的

如何保持sql依存关系的目的

本文介绍了如何保持sql依存关系的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序.

I have a console application.

我想继续观察数据库表中特定列的更改.

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

我通过Internet进行了阅读,发现sql依赖对我的目的是有益的.我开始学习它,并做了以下工作:

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. 创建一个类.
  2. 在构造函数中,我调用了静态函数 start ,并调用了具有所有sql依赖项设置的函数.
  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.

我的问题

当我使用 start 运行应用程序时,在Visual Studio 2013上单击,应用程序将运行,然后停止.但是,我需要的是这些应用程序开始运行并一直在监视数据库表中的更改.

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.

你能帮我吗?

这是非常非常非常简单的C#代码.

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();
        }

推荐答案

问题在于没有重新订阅.您应该在 OnDependencyChange 内调用 listen 方法.我知道这很奇怪,但是它是SqlDependency类.

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.

这篇关于如何保持sql依存关系的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 12:00