SqlDependency OnChange Not Firing

两盒软妹~` 提交于 2019-11-29 05:03:42

I'm hoping that its a stupid mistake I've made.

Unfortunately (or fortunately?) you are making several mistakes.

  1. First is you need to understand that Query Notifications will invalidate one query. So you will only be notified at most once and you have to re-subscribe again (re-submit the query) if you want to receive further notifications.

  2. Next you need to understand that you will be notified for any reason, not only for changes. In your callback you must check the reason you're notified, which are passed in via the SqlNotificationEventArgs.

  3. Next you need to understand asynchronous programming basic principles: if you subscribe for an event make sure you subscribe before the event can happen first time. Case in point: the On_SqlBitChanged can fire as soon as you submit the query. This should happen in the SqlWatcher.SqlWatcher constructor, but you subscribe to the sqlWatcher.NewMessage after the constructor runs. On_SqlBitChanged can be invoked between the constructor finishes before you hook up the NewMessage event callback in which case the notification is silently ignored.

  4. If you want to use a service make sure you start it before you use it. You are using SqlDependency in SqlWatcher.SqlWatcher but you start it after that when you call SqlWatcher.Start().

  5. Finally, if you want to be notified of changes on a query you have to submit the query. You are constructing the SqlCommand object, set up the notification and then... discard the object. Unless you actually submit the query, you did not yet subscribed to anything.

Suggestions for fix:

  • Make Start and Stop statics, call Start in application start up.
  • Make sure you subscribe to NewMessage before you submit the query
  • Actually submit the query (call SqlComamnd.ExecuteQuery())
  • Inspect the Info, Type and Source in the On_SqlBitChanged callback, if your submission contains an error this is the only way to learn (the SqlComamnd.ExecuteQuery() will succeed even if the notification request is invalid)
  • You must re-subscribe once you're notified of a change, execute the query again.

One more thing: don't invoke UI code in background callbacks. You cannot call MessageBox.Show("Message Received"); from a callback, you must route through the form main thread via Form.Invoke. YEs, I know that strictly speaking MessageBox.Show does work on a non-UI thread but you will soon move away from alert boxes to actually form interaction and then things will break.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!