0

SQL Server 通知を使用して、Windows サービス内のデータベースで挿入/更新イベントをキャプチャしたいと考えています。SQLDependency オブジェクトを使用しようとしています。MSDN の記事を見ると、これはかなり単純明快に思えます。そこで、試してみるために小さなサンプル アプリケーションを作成しました。テーブルのデータに変更を加えると、OnChange イベントが発生しないように見えます。誰かが私に欠けているものを教えてもらえますか? ありがとう!私のコードのサンプルは以下のとおりです。

private bool CanRequestNotifications()
{
    SqlClientPermission permit = new
    SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
    try
    {
        permit.Demand();
        return true;
    }
    catch (System.Exception exc)
    {
        return false;
    }
}

private void NotificationListener()
{
    string mailSQL;
    SqlConnection sqlConn;
    try
    {
        string connString = "Data Source=xyz;Initial Catalog=abc;User ID=sa;Password=******";
        mailSQL = "SELECT * FROM [tbl_test]";

        SqlDependency.Stop(connString);
        SqlDependency.Start(connString);

        sqlConn = new SqlConnection(connString);
        SqlCommand sqlCmd = new SqlCommand(mailSQL, sqlConn);
        this.GetNotificationData();
        evtLog.WriteEntry("Error Stage: NotificationListener" + "Error desc:" + "Message", EventLogEntryType.Error);
    }
    catch (Exception e)
    {
        // handle exception
    }
}

private void GetNotificationData()
{
    DataSet myDataSet = new DataSet();
    SqlCommand sqlCmd = new SqlCommand();
    sqlCmd.Notification = null;

    SqlDependency dependency = new SqlDependency(sqlCmd);
    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
    evtLog.WriteEntry("Error Stage: GetNotificationData" + "Error desc:" + "Message", EventLogEntryType.Error);
}

private void dependency_OnChange(object sender,SqlNotificationEventArgs e)
{
    SqlDependency dependency = (SqlDependency)sender;
    dependency.OnChange -= dependency_OnChange;
    this.GetNotificationData();
    evtLog.WriteEntry("Error Stage: dependency_OnChange" + "Error desc:" + "Message", EventLogEntryType.Error);
}

protected override void OnStart(string[] args)
{
    CanRequestNotifications();
    NotificationListener();
}

protected override void OnStop()
{
    SqlDependency dependency = new SqlDependency();
    dependency.OnChange -= dependency_OnChange;
    SqlDependency.Stop(connString);
}
4

1 に答える 1

0

SqlDependency操作ごとに新しいインスタンスを使用しているようです。これは長期的には機能しません。あなたはそれを必要とするコードのそれらの部分にアクセス可能な単一のインスタンスへの参照を持っているべきです-これはあなたの問題を解決するのに役立つかもしれません。

また、データを変更していることを実際に確認することはできません。接続とコマンドを作成しますが、実行はありません。

于 2011-09-06T12:21:56.220 に答える