开发者

How can I use SqlDependency in a class?

I have a big problem. When I implement a SqlDependency watcher in a windows form, everything works fine as long as I invoke my "OnChance" event to the ui thread.

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
  if (this.InvokeRequired)
  {
    OnChangeEventHandler tempDelegate = new OnChangeEventHandler(dependency_OnChange); object[] args = { sender, e };
    this.Invoke(tempDelegate, args);
    return;
  }

  SqlDependency dependency = (SqlDependency)sender;
  dependency.OnChange -= d开发者_开发技巧ependency_OnChange;
  SetSqlWatcher();
}

If I move my methods to a class, I'm not able to do Invoke and InvokeRequired, because my class does not implement ISynchronizeInvoke. If I comment these lines, the program hangs at the first line in "SetSqlWatcher":

SqlDependency.Stop("Data Source=[....]");

The same happens when I comment these lines in the windowsform, so I think that the _OnChance Event is on a different thread than the "thread" I'm using when I call SetSqlWatcher the first time.

I also tried to implement ISynchronizeInvoke (with the help of GenericSynchronizingObject in libary http://nitoasync.codeplex.com). I debugged, saw, that the code has to invoke it the first time, but it also hangs in "SqlDependency.Stop"...

Is someone able to help me out, and maybe explain me why this can not work?

Thank you very much! Best regards Thomas


Yeah, I found it out myself :) If anyone runs into the same problem: I solved it using an own thread, that is "informed" with a AutoResetEvent when it has to reinitiate the SqlDependency:

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
  SqlDependency dependency = (SqlDependency)sender;
  dependency.OnChange -= dependency_OnChange;
  autoEvent.Set();
}

public void ThreadWorker(object data)
{
  while (true)
  {
    SetSqlWatcher();

    autoEvent.WaitOne();
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜