问题描述
我有一个控制台应用程序.
I have a console application.
我想继续观察我的数据库表中特定列的变化.
I wanna keep watching the changes on a specific column in my database table.
我通过互联网阅读,发现 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:
- 创建一个类.
- 在构造函数中,我调用了静态函数
start
,并调用了一个具有所有sql依赖设置的函数.
- create a class.
- 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 运行应用程序时,应用程序运行然后停止.但是,我需要的是应用程序开始工作并持续关注我的数据库表中的更改.
Myproblem
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 依赖项发挥其作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!