title: SqlDependency constant database hits
body: <p>I have just copied the example from an official Microsoft source <a href="http://msdn.microsoft.com/en-us/library/a52dhwx7(v=vs.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/a52dhwx7(v=vs.80).aspx</a> and I am baffled by it. Having run the application, it makes constant database hits even though nothing is using that table? I thought when that table actually changes the event will fire? I don't want it to make constant DB calls every second, that is awful.</p>
  
  <p>Have I done something wrong? I imagine I have not sure what though. Anybody have a link to a good example preferably not MSDN.</p>
  
  <p>Thanks in advance, Onam.</p>
  
  <p>This is the SQL:</p>
  
  <pre><code>return "SELECT [ID],[FromMachine],[FromStore],[FromUser] FROM dbo.Store_Message";
  </code></pre>
  
  <p>As requested, all code:</p>
  
  <pre><code>    public partial class Form1 : Form
  {
      string connectionString = "server=localhost;database=usicoal;uid=admin;password=";
  
      public Form1()
      {
          InitializeComponent();
      }
  
      private void Form1_Load(object sender, EventArgs e)
      {
          GetNames();
      }
  
      private bool DoesUserHavePermission()
      {
          try
          {
              SqlClientPermission clientPermission = new SqlClientPermission(PermissionState.Unrestricted);
              clientPermission.Demand();
              return true;
          }
          catch
          {
              return false;
          }
      }
  
      void dep_OnChange(object sender, SqlNotificationEventArgs e)
      {
          if (this.InvokeRequired)
          {
              this.BeginInvoke(new MethodInvoker(GetNames));
          }
          else
          {
              GetNames();
          }
          SqlDependency dep = sender as SqlDependency;
          dep.OnChange -= new OnChangeEventHandler(dep_OnChange);
      }
  
      private void GetNames()
      {
          if (!DoesUserHavePermission())
              return;
  
          SqlDependency.Stop(connectionString);
          SqlDependency.Start(connectionString);
  
          using (SqlConnection cn = new SqlConnection(connectionString))
          {
              using (SqlCommand cmd = cn.CreateCommand())
              {
                  cmd.CommandType = CommandType.Text;
                  cmd.CommandText = "SELECT ID FROM dbo.[BTE_SIMPLE_STORE_MESSAGE]";
                  cmd.Notification = null;
  
                  SqlDependency dep = new SqlDependency(cmd);
                  dep.OnChange += new OnChangeEventHandler(dep_OnChange);
  
                  cn.Open();
  
                  using (SqlDataReader dr = cmd.ExecuteReader())
                  {
                      while (dr.Read())
                      {
                      }
                  }
              }
          }
      }
  }
  </code></pre>