SQL依赖关系触发多次

时间:2019-07-03 17:08:02

标签: c# sqldependency

SQL依赖项会触发多次。第一次打开主窗体时,它会完美运行,但是当我输入一个窗体并返回主窗体时,它将触发两次,而当我再次输入该窗体时,它将触发三遍,依此类推。

public partial class Form1 : Form
{       
    public string connectionstring = "my connection string";

    public Form1()
    {           
        SqlDependency.stop(connectionstring);
        SqlDependency.Start(connectionstring);
        InitializeComponent();      
        not();       
    }

    public void not()
    {
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();

        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT id,noofflight, pnr, details FROM dbo.tbl_fls;";
        cmd.Notification = null;

        SqlDependency dependency = new SqlDependency(cmd);
        dependency.OnChange -= new

        OnChangeEventHandler(OnDependencyChange);  //unsubscribe the old event

        dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);// //subscribe new event

        SqlDataReader a = cmd.ExecuteReader();

        while (a.Read())
        {
            // Doing something here...
        }           

        con.Close();
    }

    public void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {    
        if (e.Info == SqlNotificationInfo.Insert)
        {
            notifyIcon1.Icon = SystemIcons.Application;
            notifyIcon1.BalloonTipText = "there is a change ";
            notifyIcon1.ShowBalloonTip(15000);
            notifyIcon1.Icon = SystemIcons.Warning;
            //notify the user               
        }
        //do nothing!! 
    }

    not();
}

0 个答案:

没有答案