WPF非轮询方式实时更新数据库变化SqlDependency

(1)启用当前数据库的 SQL Server Service Broker

alter database 数据库名称 set enable_broker

若命令执行成功的话,验证一下,执行下面SQL语句

select IS_BROKER_ENABLED from master.sys.databases

where name='数据库名称'

值为1表示开启,为0表示未开启 

(2)后台代码

    public partial class Page1 : Page
    {
        private static string connStr;
        SqlDataReader sdr;
        public Page1()
        {
            InitializeComponent();
            connStr = 数据库连接字符串

            SqlDependency.Start(connStr);//传入连接字符串,启动基于数据库的监听
            UpdateUI();
        }

        private void UpdateUI()
        {
            using (SqlConnection connection = new SqlConnection(connStr))
            {
                //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
                //获取要监控的数据内容,这里只监控一条数据
                using (SqlCommand command = new SqlCommand("select ID,UserID,[Message] From [dbo].[Messages] where ID=2", connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    SqlDependency dependency = new SqlDependency(command);
                    //当后台数据库发生变化时,触发该事件
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    sdr = command.ExecuteReader();
                    while (sdr.Read())
                    {
                        //线程安全,使用Dispatch线程更新界面
                        DispatchUpdateUI(sdr);
                    }
                    sdr.Close();
                }
            }
        }

        private void DispatchUpdateUI(SqlDataReader sdr)
        {
            try
            {
                tbxUserID.Dispatcher.Invoke(new UpdatetbxUserDelegate(UpdatetbxUserIDAction));
                tbxMessage.Dispatcher.Invoke(new UpdatetbxMessageDelegate(UpdatetbxMessageAction));
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        private delegate void UpdatetbxUserDelegate();
        private delegate void UpdatetbxMessageDelegate();

        private void UpdatetbxUserIDAction()
        {
            tbxUserID.Text = sdr["UserID"].ToString();
        }
        private void UpdatetbxMessageAction()
        {
            tbxMessage.Text = sdr["Message"].ToString();
        }
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            UpdateUI();
        }

    }

DataReader始终和数据库连接,当检测数据发生变化时,触发OnChange 事件,编写后台逻辑,获取数据库的本地副本,这里使用数据绑定(ObservableCollection<T>)发现无法实时更新到客户端,有待继续研究,暂时采用了手动刷新界面的方式,涉及到了Dispatch UI线程。
posted @ 2012-11-26 19:22  挑战  阅读(3073)  评论(0编辑  收藏  举报