【发布时间】:2023-01-26 23:52:55
【问题描述】:
大家下午好。
我正在开发一个使用 WinForms VB.NET 和 MSSQL 的项目,我需要使用 SQLDependency 来监视表中的新插入。我在测试时遇到了问题。在启动应用程序后插入一次,我确实收到了已插入内容的通知,但之后 OnChange 事件就不再被调用了。
Private Sub LoadOrder()
Dim objError As New AppFramework.Logging.EventLog
Dim objQuoOrders As New QuotationOrders.QuotationOrder
Try
objQuoOrders.Companyid = SystemCompanyId
objQuoOrders.Picker = GsUserName
objQuoOrders.InvType = "O"
ThreadSafe(Sub() gcOrders.DataSource = objQuoOrders.GetOrdersByPicker())
Catch ex As Exception
MessageBox.Show(ex.Message, "LoadOrder", MessageBoxButtons.OK, MessageBoxIcon.Error)
objError.LogError(SystemApplicationLogSource, "AceFinancials", ex)
End Try
End Sub
Private Sub ActivateDependency()
Dim objError As New AppFramework.Logging.EventLog
Try
If sqlConnection IsNot Nothing AndAlso sqlConnection.State = ConnectionState.Open Then sqlConnection.Close()
sqlConnection = New SqlConnection(AppFramework.Database.Connection.ConnectionString)
sqlConnection.Open()
SqlDependency.Stop(AppFramework.Database.Connection.ConnectionString)
SqlDependency.Start(AppFramework.Database.Connection.ConnectionString)
Using cmd As SqlCommand = New SqlCommand(" Select tb_quotation_notifications.notification_id, tb_quotation_notifications.notification_invid
From dbo.tb_quotation_notifications
Where tb_quotation_notifications.notification_picker_id = " & UserID &
" And tb_quotation_notifications.company_id = " & SystemCompanyId, sqlConnection)
Dim dependency As SqlDependency = New SqlDependency(cmd)
AddHandler dependency.OnChange, AddressOf dependency_OnChange
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "ActivateDependency", MessageBoxButtons.OK, MessageBoxIcon.Error)
objError.LogError(SystemApplicationLogSource, "AceFinancials", ex)
End Try
End Sub
Private Sub dependency_OnChange(sender As Object, e As SqlNotificationEventArgs)
Dim objError As New AppFramework.Logging.EventLog
Try
If e.Info = SqlNotificationInfo.Insert Then
NotificationManager.ShowNotification(NotificationManager.Notifications(0))
LoadOrder()
ActivateDependency()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "dependency_OnChange", MessageBoxButtons.OK, MessageBoxIcon.Error)
objError.LogError(SystemApplicationLogSource, "AceFinancials", ex)
End Try
End Sub
Private Sub ThreadSafe(method As MethodInvoker)
Dim objError As New AppFramework.Logging.EventLog
Try
If (InvokeRequired) Then
Invoke(method)
Else
method()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "ThreadSafe", MessageBoxButtons.OK, MessageBoxIcon.Error)
objError.LogError(SystemApplicationLogSource, "AceFinancials", ex)
End Try
End Sub
如果您需要更多信息,我会适当更新我的问题
【问题讨论】:
-
依赖关系在它触发后被删除。您需要再次激活。
-
@DanGuzman 我已经更新了我的代码,但是对于更新版本,
SqlDependency.Stop()非常慢......就像 39,658ms 只是为了移动到 SqlDependency.Start()。 -
您不需要每次都停止/启动依赖项,只需再次执行依赖项的查询即可。在应用程序启动时调用
Start(),在应用程序终止时调用Stop()。见this answer。 -
@DanGuzman 感谢您提供的提示,使我免于此难。万分敬意!
标签: sql-server vb.net sqldependency