(1) 啟用當(dāng)前數(shù)據(jù)庫的 SQL Server Service Broker
alter database 數(shù)據(jù)庫名稱 set enable_broker
若命令執(zhí)行成功的話,驗證一下,執(zhí)行下面 SQL 語句
select IS_BROKER_ENABLED from master . sys.databases
where name = '數(shù)據(jù)庫名稱'
??? public partial class Page1 : Page
??? {
??????? private static string connStr;
??????? SqlDataReader sdr;
??????? public Page1()
??????? {
??????????? InitializeComponent();
??????????? connStr =?數(shù)據(jù)庫連接字符串
??????????? SqlDependency.Start(connStr);//傳入連接字符串,啟動基于數(shù)據(jù)庫的監(jiān)聽
??????????? UpdateUI();
??????? }
??????? private void UpdateUI()
??????? {
??????????? using (SqlConnection connection = new SqlConnection(connStr))
??????????? {
??????????????? //依賴是基于某一張表的,而且查詢語句只能是簡單查詢語句,不能帶top或*,同時必須指定所有者,即類似[dbo].[]
??????????????? //獲取要監(jiān)控的數(shù)據(jù)內(nèi)容,這里只監(jiān)控一條數(shù)據(jù)
??????????????? 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);
??????????????????? //當(dāng)后臺數(shù)據(jù)庫發(fā)生變化時,觸發(fā)該事件
??????????????????? 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();
??????? }
??? }
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
