SQL зависимость срабатывает много раз - PullRequest
0 голосов
/ 03 июля 2019

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