【发布时间】:2015-06-18 09:16:51
【问题描述】:
我想在我的 winforms 应用程序中使用 SqlDependency 类:
public partial class Form1 : Form
{
private int changeCount = 0;
private const string statusMessage = "{0} changes have occurred.";
private static SqlConnection connection = null;
private static SqlCommand command = null;
private static SqlDependency dependency;
private static SqlCommand command1 = null;
private static SqlDependency dependency1;
public Form1()
{
InitializeComponent();
button1.Enabled = CanRequestNotifications();
this.FormClosed += Form1_FormClosed;
if (connection == null)
{
connection = new SqlConnection(GetConnectionString());
}
if (command == null)
{
command = new SqlCommand("procCreationUser", connection);
command.CommandType = CommandType.StoredProcedure;
}
dependency = new SqlDependency(command);
if (connection == null)
{
connection = new SqlConnection(GetConnectionString());
}
if (command1 == null)
{
command1 = new SqlCommand("procSelectionUser", connection);
command1.CommandType = CommandType.StoredProcedure;
}
dependency1 = new SqlDependency(command1);
GetData();
}
private void GetData()
{
SqlDependency.Start(GetConnectionString());
if (connection.State != ConnectionState.Open) connection.Open();
using (var dr = command.ExecuteReader())
{
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
}
using (var dr = command1.ExecuteReader())
{
dependency1.OnChange += new OnChangeEventHandler(dependency_OnChange);
}
}
private string GetConnectionString()
{
return @"Data Source=PRT-12\SQLEXPRESS; Initial Catalog=TestNotification;Integrated Security=True";
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MessageBox.Show("Notification");
}
}
我创建了两个存储过程:procCreationUser 用于创建,procSelectionUser 用于选择用户。
当我启动应用程序时,我点击了按钮并在数据库中插入了一个新行,我没有收到任何通知!!!!!
- 如何修复我的代码?
- 这是从 Sql Server 获取通知的最佳方式吗?
【问题讨论】:
-
你需要整理你的代码,它有点到处都是。
-
@artm 请看我的编辑
-
您是否在数据库中启用了 Service Broker。
-
@DevD 是的,它已激活
-
你还有一些不必要的代码,为什么你需要一个
using reader围绕dependency.onChange()?看起来您的编辑还删除了更新数据的代码?
标签: c# sql .net sql-server service-broker