在winform SqlDependency.OnChange不触发? [英] SqlDependency.OnChange not firing in WinForm?
问题描述
我用用的SqlDependency检测更改为例为我写的代码。我也看了类似的代码等各个环节,但他们没有工作。
I used Detecting Changes with SqlDependency as example for the code that I'm writing. I've also looked at other links with similar code, but none of them work.
从本质上讲,我只是想更改 label1.Text
更改时已表发 [错误日志]
。出于某种原因, OnDependencyChange
不点火。
Essentially, I simply want to change label1.Text
when a change has been made to table [ErrorLog]
. For some reason, OnDependencyChange
is not firing.
我已经启用服务代理
数据库中的:
I've enabled Service Broker
in the database:
ALTER DATABASE TestDB
SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
现在,这里是我的完整代码。这是非常短的:
Now, here's my complete code. It's very short:
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:
I checked if service broker is enabled and it is; the following returns 1:
SELECT is_broker_enabled
FROM sys.databases
WHERE name = 'TestDB';
任何帮助表示赞赏。
Any help is appreciated.
谢谢
推荐答案
您正确地做一切,除了一件事。调用方法的someMethod()
在 Form1中
构造一次。
You are doing everything correctly except one thing. Call the method SomeMethod()
once in your Form1
constructor.
所有的后续更改您的表中的数据将触发依赖的变化。
All subsequent changes to your table data will trigger the dependency change.
这篇关于在winform SqlDependency.OnChange不触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!