(1) 啟用當前數據庫的 SQL Server Service Broker
alter database 數據庫名稱 set enable_broker
若命令執行成功的話,驗證一下,執行下面 SQL 語句
select IS_BROKER_ENABLED from master . sys.databases
where name = '數據庫名稱'
??? 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();
??????? }
??? }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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