如何从SQL Server内存中清除SqlDependency?如何清理SQL Server以清除过期的SqlDependency对象?从SqlDepedency对象收到事件后,我需要创建一个新事件才能获得新事件。但是,SQL Server进程的内存使用量会增加,直到超出允许的内存(SQL Server Express)。如何摆脱旧查询?码:// Func: RegisterTableListenerusing (SqlConnection cn = new SqlConnection(Properties.Settings.Default.DatabseEventConnectionString)){if (cmd == null){
cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT HostName, LastStatus, LastDetails, xml FROM dbo.[SystemTable]";}lock (cmd){
cmd.Connection = cn;
cn.Open();
cmd.Notification = null;
// creates a new dependency for the SqlCommand
if (dep == null)
dep = new SqlDependency(cmd);
// creates an event handler for the notification of data
// changes in the database.
dep.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (SqlDataReader reader = cmd.ExecuteReader())
{
// code here to read
}}}// Func dependency_OnChange//SqlDependency dep = sender as SqlDependency;dep.OnChange -= dependency_OnChange;RegisterTableListener();
2 回答
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
Microsoft SqlDependency类有一个特定的行为。即使您调用SqlDependency.Stop()方法,释放SqlCommand和SqlConnection - 它仍然保留数据库中的会话组(sys.conversation_groups)和会话端点(sys.conversation_endpoints)。看起来SQL Server加载每个会话端点并使用所有允许的内存。这里测试证明了这一点。因此,要清除所有未使用的会话端点并释放所有占用的内存,您必须为数据库启动此SQL代码:
DECLARE @ConvHandle uniqueidentifier DECLARE Conv CURSOR FOR SELECT CEP.conversation_handle FROM sys.conversation_endpoints CEP WHERE CEP.state = 'DI' or CEP.state = 'CD'OPEN Conv;FETCH NEXT FROM Conv INTO @ConvHandle;WHILE (@@FETCH_STATUS = 0) BEGIN END CONVERSATION @ConvHandle WITH CLEANUP; FETCH NEXT FROM Conv INTO @ConvHandle;ENDCLOSE Conv;DEALLOCATE Conv;
此外,SqlDependency不会让您有机会接收表的所有更改。因此,在SqlDependency重新订阅期间,您不会收到有关更改的通知。
为了避免所有这些问题,我使用了另一个SqlDependency类的开源实现--SqlDependencyEx。它使用数据库触发器和本机Service Broker通知来接收有关表更改的事件。这是一个用法示例:
int changesReceived = 0;using (SqlDependencyEx sqlDependency = new SqlDependencyEx( TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME)) { sqlDependency.TableChanged += (o, e) => changesReceived++; sqlDependency.Start(); // Make table changes. MakeTableInsertDeleteChanges(changesCount); // Wait a little bit to receive all changes. Thread.Sleep(1000);}Assert.AreEqual(changesCount, changesReceived);
希望这可以帮助。
- 2 回答
- 0 关注
- 815 浏览
添加回答
举报
0/150
提交
取消