SqlNotificationEvent多次通知数据库中的单个插入

时间:2012-04-18 07:27:54

标签: c# sql-server performance sqlcachedependency

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

2 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:-1)

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

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

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