【发布时间】:2016-06-25 04:10:41
【问题描述】:
我使用Detecting Changes with SqlDependency 作为我正在编写的代码的示例。我还查看了具有类似代码的其他链接,但它们都不起作用。
本质上,当表[ErrorLog] 发生更改时,我只想更改label1.Text。出于某种原因,OnDependencyChange 没有触发。
我在数据库中启用了Service Broker:
ALTER DATABASE TestDB
SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
现在,这是我的完整代码。很短:
public partial class Form1 : Form
{
private string GetConnectionString()
{
return @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=TestDB;Persist Security Info=True;User ID=TestUser;Password=12345;";
}
SqlConnection connection;
public Form1()
{
InitializeComponent();
connection = new SqlConnection(GetConnectionString());
connection.Open();
SqlDependency.Start(GetConnectionString());
i = 0;
}
int i;
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
i++;
label1.Text = "Changed: " + i.ToString();
// Handle the event (for example, invalidate this cache entry).
}
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
using (SqlCommand command =
new SqlCommand("SELECT [ErrorLog].[ID],[ErrorLog].[Project],[ErrorLog].[Form],[ErrorLog].[Message],[ErrorLog].[Exception],[ErrorLog].[InsertDate] " +
"FROM [dbo].[ErrorLog]", connection))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency = new SqlDependency(command);
// Maintain the reference in a class member.
// Subscribe to the SqlDependency event.
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
// Execute the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// Process the DataReader.
}
}
}
}
我检查了服务代理是否已启用并且已启用;以下返回 1:
SELECT is_broker_enabled
FROM sys.databases
WHERE name = 'TestDB';
感谢任何帮助。
谢谢。
【问题讨论】:
标签: c# winforms visual-studio-2010 sql-server-2008-r2