0

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();
    }
4

2 回答 2

0

您可以使用SqlNotificationEventArgs对象的SqlNotificationInfo对象并检查它是否为 Insert、Update 或 Delete 并忽略其余部分。

public static void OnNotificationChange(object caller, SqlNotificationEventArgs e)
{
    if (e.Type == SqlNotificationType.Change && (e.Info == SqlNotificationInfo.Insert || e.Info == SqlNotificationInfo.Delete || e.Info == SqlNotificationInfo.Update))
    {
        SqlDependency dependency =(SqlDependency)sender;
        dependency.OnChange -= OnNotificationChange;
        RegisterForChanges();
    }
}
于 2012-04-18T07:38:09.990 回答
-1

我遇到了与问题中描述的相同的问题。我能够确定问题是由创建多个SqlCommand实例引起的(类似于您在using (SqlCommand oCommand = new SqlCommand("dbo.GetUsers", oConnection))内部RegisterForChanges()的 .

我更改了代码以声明对SqlCommandSqlConnection对象的实例引用,并仅SqlDependencyRegisterForChanges()方法中实例化新实例。

void RegisterForChanges()
{
  _sqlCommand.Notification = null;
  _sqlConnection.Open();
  SqlDependency dependency = new SqlDependency(_sqlCommand);
  dependency.OnChange += dependency_OnChange;
  _sqlCommand.ExecuteNonQuery(); // or ExecuteReader and parse the results, etc
  _sqlConnection.Close();
}
于 2014-02-28T16:11:30.283 回答