Timeout expired when querying SQL Server via NHibernate

半世苍凉 提交于 2019-12-04 21:09:06

This would cause the issue:

begin transaction 

update Documents
set SomeField = 'SomeValue'
where SomeCondition = 'XXXX'

select top 10 Id, Name from Users

commit

The locks created on the document table during the update won't be released until you commit the transaction. This would mean that a connection could have the select statement as its most recent statement, but still be holding locks from the previous update.

Some ideas:

  1. Make sure you are committing/rolling back your transactions
  2. Try to reduce the length of your transactions (e.g. in the above, would it be safe to commit before running the select?).
  3. Optimizing the join on the update by making sure the foreign key is indexed might also speed up the transaction.

Note that a select itself will only generate shared locks.

Finally beware of the (nolock) lock hint idea. Reading uncommitted data is rarely a good idea.

A SQL Server gotcha is a non-default "isolation-level" setting on the database. SQL Server has a default isolation-level (locking strategy) of ReadCommitted which means that read locks are released as soon as possible but write locks are not released until a transaction is committed. In Andy's answer, the default isolation-level will cause the select to be blocked. However if the database is set to either RepeatableRead or Serializable, then selects will always block each other for the duration of a transaction. This setting can be controlled in NHibernate with this hibernate.cfg.xml config:

<session-factory>
    ...
    <add key="hibernate.connection.isolation" value="ReadCommitted" />
    ...
</session-factory>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!