开发者

What is the relationship between open SqlConnections in the client app and processes in SQL Server?

I just tried to make a simple schema change to a table in a SQL Server database (by using the Design tool in SMSS). Whenever I tried to save the change, it kept timing out. I wondered whether this was due to existing connnections which were 'locking' the table.

I decided to kill connections as an experiment. I queried master..sysprocesses to get the current spids for that database, and killed them one by one until I was able to save my schema change. (Not very scientific, but I'm far from an expert with SQL Server). Sure enough, when I had killed all the spids (bar the one which was me using SMSS), I was able to save the schema change.

I would like to ask about the relationship between ADO.NET SqlConnections and spids. For example, if the client app calls Open() on a SqlConnection object, should I see another spid in master..sysprocesses? What about if I call Close() on that SqlConnection? Should the开发者_Python百科 spid disappear?

I'm sure it's not quite that simple, since I understand there is a notion of connection pooling, but can someone shed any light on how this relationship works?

Thank you

David


If pooling=false in the connection string

SqlConnection.Open() and Close() will exactly correlate to spids being created and destroyed. This results in very slow performance :)

If pooling=true in the connection string

Calling SqlConnection.Open() will either use an existing physical connection from the pool, or create a new one if none are available in the pool.

Creating a new physical connection will create a new spid, which will show up as a new row in sys.sysprocesses and sys.dm_exec_connections.

Reusing an existing pooled physical connection will just reuse an existing spid so you SqlConnection.Open() will not make any visible change in those tables on the server side. However it can be detected by using SQL Profiler or XEvent by looking for sp_reset_connection, which is a stored procedure called by SqlClient that tells the server to clear the connection state (e.g. make sure there is no transaction, etc).

SqlConnection.Close() will usually return the physical connection to the pool, so it will not disappear from the server. Physical connections are actually closed in various ways under the hood, such as by being killed by the server such as kill @spid and SqlConnection.ClearAllPools().

Hope that is enough detail, is there anything else you'd like to know?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜