c# - 为什么 sysprocesses 在 SQL Server 上长时间处于打开状态?

标签 c# sql-server nhibernate connection-pooling

我注意到我的生产 SQL Server 上有很多数据库连接处于打开状态,有些连接时间很长。其中许多都有公开交易。如查询中所示:

select * from sysprocesses where open_tran>0

它们处于状态 =“ sleep ”,cmd =“等待命令”。

使用 NHIBERNATE 打开连接如下:

For<ISessionFactory>().Singleton()
    .Use(() => DataContext.GetSessionFactory());

For<ISession>().Transient()
  .Use(context => context.GetInstance<ISessionFactory>().OpenSession());

一些 session 使用事务范围: _transactionScope = new TransactionScope();

有些创建交易:

_uncommittedTransaction = SessionUncommittedWrapper.Session.BeginTransaction(IsolationLevel.ReadUncommitted);

transaction 和/或 transactionScope 在之后处理。

为什么连接仍然打开?如果什么都没有被阻止,这是一个问题吗?

最佳答案

They are in status = "sleeping", cmd = "AWAITING COMMAND".

当您在 sysprocesses 中看到一行状态为 sleep 时,这意味着此连接处于事件状态,但未被使用。这也是由于 connection Pooling mechanism 而发生的。由 SQLServer 使用..

等待命令可以用下面的例子来解释..

session 1:开始此事务

begin tran
insert into sometable
select some columns

现在,当您在 sys.processes/session DMV 中检查 session1 的状态时,您可以看到它是 Awaiting command..因为,您没有提交它。

等待命令的另一个原因可能是当您开始交易并等待用户输入时

begin tran
update t
set t1.a=<<some input from user>>--waiting
where t1.a=oldvalue
commit

And is it a problem, if nothing is being blocked?

只要您看到没有任何东西被阻塞, sleep 和 session 没有持有任何锁并且您没有看到任何打开的事务,您就不必担心。这由 Bob Dorr in this article 解释。 ..

The question usually arises around a session that is holding locks and its state is sleeping / awaiting command. If the client has an open transaction and the client did not submit a commit or rollback command the state is sleeping / awaiting command. I see this quite often with a procedure that times out.

Create proc myProc
As
Begin tran
Update authors ….
 Waitfor delay ’10:00:00’   — time out will occur here  (simulates long workload)
 rollback
go

When run from the client with a 30 second query timeout the transaction will remain open because the client indicated it wanted to ‘cancel execution’ and do no further processing.

To get automatic rollback in this situation transaction abort must be enabled. You now have an open transaction with a SPID sleeping/awaiting command. The situation can be caused by many other variations but it is always a situation where the SQL Server is waiting for the next command from the client

关于c# - 为什么 sysprocesses 在 SQL Server 上长时间处于打开状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39705010/

相关文章:

c# - 检测字符串中的回车

c# - 我如何在 NHibernate 中进行通用字段和组件级更改跟踪?

.net - NHibernate 在保存时自动设置属性

nhibernate - QueryOver - JoinQueryOver 问题

c# - 如何创建这样的任务面板?

c# - WPF Helix如何在代码中使用 "zoom extent"viewport3d?

sql - 让 AVG() 忽略 0?

sql-server - SQL Server : Remove rows with a different aggregate (where or having)

asp.net - asp.net中导出大量数据到客户端

c# - Unity 中的鼠标弹起与触摸弹起