【发布时间】:2020-02-18 10:18:28
【问题描述】:
我开发了一个使用 SqlDependency 作为 Windows 服务的程序。但它不起作用。 我在 SQL 服务中有表 dbo.Product。我希望当此表的任何记录更新时,我会收到通知。
命名空间 MyService { 公共部分类Service1:ServiceBase { string connectionString = "数据源=.\myserver;初始目录=mydb;用户ID=用户;密码=pass;"; 静态 int itemref; 静态小数?数量; public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
RegisterNotification();
}
private void RegisterNotification()
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
using (SqlTableDependency<ItemStockSummary> tableDependency = new SqlTableDependency<ItemStockSummary>(connectionString))
{
tableDependency.OnChanged += TableDependency_Changed;
tableDependency.Start();
}
}
void TableDependency_Changed(object sender, RecordChangedEventArgs<ItemStockSummary> e)
{
if (e.ChangeType != ChangeType.None)
{
var changedEntity = e.Entity;
itemref = changedEntity.ItemRef;
quantity = changedEntity.Quantity;
UpdateProduct(itemref, quantity);
}
}
void OnDataChange(object sender, SqlNotificationEventArgs e)
{
((SqlDependency)sender).OnChange -= OnDataChange;
UpdateProduct(itemref, quantity);
RegisterNotification();
}
protected override void OnStop()
{
SqlDependency.Stop(connectionString);
}
public void UpdateProduct(int item, decimal? quantity)
{
\\Do something
}
}
【问题讨论】:
-
您好,欢迎您。请通过提供您收到的任何错误消息的详细信息来帮助其他人回答您的问题。此外,您的代码格式有点偏离。查看格式指南 (stackoverflow.com/help/formatting)
标签: c# sql-update windows-services