问题描述
usingSystem;usingSystem.Configuration;usingSystem.Data;usingSystem.Data.SqlClient;namespaceSqlDependencyTest{classProgram{privatestaticstring_connStr;staticvoidMain(string[]args){_connStr=ConfigurationManager.ConnectionStrings["ConnStr"].ToString();SqlDependency.Start(_connStr);//傳入連接字元串,啟動基於資料庫的監聽UpdateGrid();Console.Read();}privatestaticvoidUpdateGrid(){using(SqlConnectionconnection=newSqlConnection(_connStr)){//依賴是基於某一張表的,而且查詢語句只能是簡單查詢語句,不能帶top或*,同時必須指定所有者,即類似[dbo].[]using(SqlCommandcommand=newSqlCommand("selectID,UserID,[Message]From[dbo].[Messages]",connection)){command.CommandType=CommandType.Text;connection.Open();SqlDependencydependency=newSqlDependency(command);dependency.OnChange+=newOnChangeEventHandler(dependency_OnChange);SqlDataReadersdr=command.ExecuteReader();Console.WriteLine();while(sdr.Read()){Console.WriteLine("Id:{0}tUserId:{1}tMessage:{2}",sdr["ID"].ToString(),sdr["UserId"].ToString(),sdr["Message"].ToString());}sdr.Close();}}}privatestaticvoiddependency_OnChange(objectsender,SqlNotificationEventArgse){UpdateGrid();}}}这是网上的代码,本人测试,数据表没有任何操作时,事件触发是死循环,但MSDN上介绍说,只有当数据表有改变时才会触发事件,初看SqlDependency,请指教