Lee*_*son 2 c# sql-server sqldependency signalr
我正在尝试SqlDependancy在SignalR项目中使用,但我似乎无法让OnChanged事件多次触发.它最初在订阅事件上触发,但在更改底层数据库后它永远不会再触发.我省略了SignalR和控制器代码,因为问题似乎在于存储库类.SqlDependancy.Start()在我Global.asax班上宣布.
从SQL服务器观察,我可以看到在我的应用程序启动时创建通知队列,并在关闭时终止.
public IEnumerable<Visitor> NotifyAllClients()
{
List<Visitor> visitors = new List<Visitor>();
using (var connection = new SqlConnection(new VisitorLogEntities().Database.Connection.ConnectionString))
{
using (var command = new SqlCommand(@"SELECT * FROM dbo.Visitors", connection))
//using (var command = new SqlCommand(@"SELECT [Id],[AgreeToTerms],[Base64Image],[CheckInDate],[CheckOutTime],[Company],[CountryOfOrigin],[email],[FirstName],[LastName],[IsInBuilding],[MeetingSubject],[MeetingTime],[PatriotHost],[phone],[title] FROM dbo.Visitors", connection))
{
var dependency = new SqlDependency(command);
dependency.OnChange += Database_OnChange;
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
////compile visitor objects
////visitors.add(new Visitor());
}
}
return visitors.OrderByDescending(x => x.CheckInDate);
}
}
private void Database_OnChange(object sender, SqlNotificationEventArgs e)
{
//var dependency = (SqlDependency)sender;
//dependency.OnChange -= Database_OnChange;
////this fires once, with the Type of 'Subscribe', but then never fires on CRUD changes
if (e.Type == SqlNotificationType.Change)
{
VisitorHub.SendVisitors();
}
//NotifyAllClients();
}
Run Code Online (Sandbox Code Playgroud)
编辑:上面注释掉的代码行表示正常工作所需的更改.
从msdn http://msdn.microsoft.com/en-US/library/a52dhwx7(v=vs.80).aspx查看此示例.下载VS2005_General_en-us.pdf.页面24636,"在Windows应用程序中使用SqlDependency"是原始链接所导致的部分.请特别注意观察者应用程序中的步骤12和13.在步骤12中,您将看到删除onChange事件,然后调用步骤13再次设置它.
此外,我认为由于你的sql语句本身你看到了不良行为.sql语句必须遵循一些规则.有关详细信息,请参阅https://technet.microsoft.com/en-us/library/ms181122(v=sql.105).aspx.特别是写通知查询部分."该语句可能不使用星号(*)或table_name.*语法来指定列."
| 归档时间: |
|
| 查看次数: |
1464 次 |
| 最近记录: |