请教SqlDependency类的运用

Dic4000 2009-01-14 12:11:08
已经对Test数据库执行了
ALTER DATABASE Test  SET enable_BROKER;


运行下面的程序后,在数据库用insert语句添加记录没得到通知.
能否看看程序哪里有误?

static void Main(string[] args)
{

InitNotify(System.Configuration.ConfigurationManager.ConnectionString["conn"].ConnectionString);
}

static void InitNotify(string connString)
{
SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
try
{
perm.Demand();
Console.WriteLine("可以建立通知");

using (SqlConnection conn = new SqlConnection(connString))
{
SqlDependency.Start(connString);
SqlCommand cmd = new SqlCommand("select item from tab",conn);
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange+= GetNotify;

DataTable dt = new DataTable("tab");

conn.Open();
dt.Load(cmd.ExecuteReader());
while (true) ;
SqlDependency.Stop(connString);
conn.Close();
}
}
catch(System.Security.SecurityException )
{

Console.WriteLine("不能建立通知");
}
}
static void GetNotify(Object sender,SqlNotificationEventArgs e)
{
Console.WriteLine("Type={0},Source={1},Inof={2}",e.Type, e.Source, e.Info);
}

...全文
69 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
sxw2006 2009-09-27
  • 打赏
  • 举报
回复
select item from tab 改为select item from dbo.tab
l 2009-04-01
  • 打赏
  • 举报
回复
试着如下修改:


dependency.OnChange+= GetNotify;
-->
dependency.OnChange += new OnChangeEventHandler(GetNotify);


另外:

查询通知有个特性:
如果在某一事务内进行了多项影响具有已注册通知请求的一组数据的修改,则仅会发送单个通知事件。
所以多个 insert ,可能只发送了一个通知


参看:

http://blog.joycode.com/ghj/archive/2009/04/01/115523.aspx
http://blog.joycode.com/sunmast/archive/2006/08/11/sql_2005_query_notification_comments_79814.aspx

110,500

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧