SQL Dependency in C#

后端 未结 1 576

I\'m trying to figure out how to use SQL Dependency (C# 4.0) to \'listen\' for changes to a database. I\'ve seen quite a few things on the web, but they seem to be tailored

1条回答
  •  礼貌的吻别
    2021-01-06 05:04

    You can hook up the SqlDependency.Change event and do whatever you like in this event handler. This is, in fact, the only way to do what you want, and there is nothing wrong with it.

    In pseudo-code it looks like this:

    var dep = new SqlDependency(GetSqlQueryForMonitoring());
    dep.Change += () => {
     var data = ExecSql(GetDataQuerySql());
     UpdateCache(data);
    };
    

    Very simple. Just use two different queries.

    Edit: In your sample code there is a comment saying you are running on the UI thread. Why should that be the case? I doubt it. Anyway, you should run your query before you resetup the dependency because otherwise you will have the potential for concurrent invalidations happening.

    I suggest you get your fresh data from the database and then send a message to the ui to update it (Invoke).

    0 讨论(0)
提交回复
热议问题