我知道通過在SQL表的更改在C#被通知的唯一方法是通過使用SqlDependencies
實施例:
private async Task RegisterSqlDependency()
{
if (_dependency != null)
_dependency.OnChange -= this.OnChange;
String query = "select MyCol from dbo.MyTable WHERE myKey = '" + _dependecyKey + "'";
using (SqlConnection connexion = new SqlConnection("ConnexionString"))
{
using (SqlCommand command = new SqlCommand(query, connexion))
{
_dependency = new SqlDependency(command, null, 0);
_dependency.OnChange += this.OnChange;
await connexion.OpenAsync();
using (SqlDataReader reader = await command.ExecuteReaderAsync())
{
while (reader.Read())
{
.... GetData ....
}
}
}
}
}
private void OnChange(object sender, SqlNotificationEventArgs e)
{
.... Data has changed on table ....
call RegisterSqlDependency() again
}
您必須在您的數據庫上啓用SERVICE BROKER以啓用SqlDepedency:
ALTER DATABASE MyDatabase SET ENABLE_BROKER with rollback immediate;
什麼樣的c#應用程序? web wpf winforms? – 2015-02-11 08:55:15
桌面應用。 C#+ WPF – 2015-02-11 09:04:01