SQL Server 通知を利用して、winform アプリ内のデータベースで挿入イベントをキャプチャしたいと考えています。SQLDependency オブジェクトを使用しようとしています。MSDN の記事を見ると、これはかなり単純明快に思えます。そこで、試してみるために小さなサンプル アプリケーションを作成しました。イベントは、最初にアプリケーションに入ったときにのみ発生するようです (MessageBox が表示されます)。テーブルにデータを挿入しても、OnChange イベントは発生しないようです。誰かが私に欠けているものを教えてもらえますか? ありがとう!
public Main()
{
InitializeComponent();
var check = EnoughPermission();
SqlDependency.Stop(constr);
SqlDependency.Start(constr);
if(connection == null)
{
connection = new SqlConnection(constr);
}
if(command == null)
{
command = new SqlCommand("Select ID, ChatMessage FROM dbo.Chat",connection);
}
connection.Open();
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
command.ExecuteReader();
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MessageBox.Show("Change!");
}