SqlNotificationEvent
データベースへの単一の挿入でも複数回通知します。
テーブル内の単一の挿入/更新/削除の場合でも、イベントは で数回通知されますがe.Type == SqlNotificationType.Change
、これが発生する理由を誰でも助けることができます。テーブルの単一の変更に対して一度だけ通知する必要があります。
static class Program
{
private static string mStarterConnectionString = "Data Source=localhost;Database=SqlDependencyTest;Persist Security Info=false;Integrated Security=false;User Id=startUser;Password=startUser";
private static string mSubscriberConnectionString = "Data Source=localhost;Database=SqlDependencyTest;Persist Security Info=false;Integrated Security=false;User Id=subscribeUser;Password=subscribeUser";
public const string CACHE_KEY = "APPCACHEKEY";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Starting the listener infrastructure...
SqlDependency.Start(mStarterConnectionString);
// Registering for changes...
RegisterForChanges();
Application.Run(new SqlCache());
// Quitting...
SqlDependency.Stop(mStarterConnectionString);
}
public static DataTable RegisterForChanges()
{
DataTable dataTable = new DataTable();
// Connecting to the database using our subscriber connection string and
// waiting for changes...
SqlConnection oConnection = new SqlConnection(mSubscriberConnectionString);
oConnection.Open();
try
{
using (SqlCommand oCommand = new SqlCommand("dbo.GetUsers", oConnection))
//using (SqlCommand oCommand = new SqlCommand("SELECT ID, Name FROM dbo.Users", oConnection))
{
oCommand.CommandType = CommandType.StoredProcedure;
SqlDependency oDependency = new SqlDependency(oCommand);
oDependency.OnChange += new OnChangeEventHandler(OnNotificationChange);
using (SqlDataAdapter adapter = new SqlDataAdapter(oCommand))
adapter.Fill(dataTable);
}
AppMain.Cache.Insert(CACHE_KEY, dataTable, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(60));
}
finally
{
oConnection.Close();
}
return dataTable;
}
public static void OnNotificationChange(object caller, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
RegisterForChanges();
}