SqlDependency常量数据库命中

时间:2013-01-15 12:22:14

标签: c# sql sqldependency

我刚刚从官方微软来源http://msdn.microsoft.com/en-us/library/a52dhwx7(v=vs.80).aspx复制了这个例子,我对它感到困惑。运行应用程序之后,即使没有使用该表,它也会产生持续的数据库命中?我以为当那张桌子真的发生变化时会发生火灾吗?我不希望它每秒都进行持续的DB调用,这很糟糕。

我做错了吗?我想我不知道是什么。任何人都有一个很好的例子的链接,最好不是MSDN。

提前致谢,Onam。

这是SQL:

return "SELECT [ID],[FromMachine],[FromStore],[FromUser] FROM dbo.Store_Message";

根据要求,所有代码:

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

2 个答案:

答案 0 :(得分:1)

SqlDependency通常按预期工作。如果数据库中的某些内容发生了变化,它会触发事件。如果查询出现问题,则会发生常量调用。使用完整的两部分表名称(例如dbo.TableName)非常重要。

MSDN文档并没有那么糟糕 - 请查看更新的article或此one版本。

答案 1 :(得分:1)

当我发现上面的代码没问题时: - 右键单击​​数据库选择属性 - 选择选项 - 设置与SQL Server 2008的兼容级别(100) - 好的

让代码正常运行。

相关问题