强制SqlConnection打开指定的持续时间 [英] Enforce SqlConnection to be open for specified duration

查看:62
本文介绍了强制SqlConnection打开指定的持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎SqlConnections在一段时间不活动后关闭.我需要能够控制连接保持打开状态的时间.可以为连接配置连接超时"和连接生存时间"属性,但是它们无法满足我的需求.

It seems that SqlConnections close after some period of time of inactivity. I need to be able to control for how long the connection remains open. There is a "connection timeout" and "Connection Lifetime" properties that can be configured for connections, but they do not do what I need.

问题是我们的应用程序很大,打开某些屏幕时,在很多地方连接都没有关闭.用户可以打开屏幕,然后去吃午餐,然后回来,然后尝试做一些事情并得到连接已丢失"异常.我知道这是一种反模式,但目前在一个地方延长连接寿命,然后在数千个地方打开/关闭和合并连接会更容易.

The problem is that our application is huge and in lots of places connections don't get closed when some screens are open. A user can open a screen, then go to lunch, then come back, then try to do something and get a "connection has been lost" exception. I know that it is an antipattern, but for now it would be easier to extend the connection lifetime in one place, then to open/close and pool connections in thousands of places.

推荐答案

您设计的应用程序非常错误.连接绝不能保持打开状态的时间不能超过一组查询(即,单个操作所需的查询)的时间.不用担心,因为SqlConnection在内部基于连接字符串池化连接,所以没有性能问题.因此,即使您打开和关闭连接,REAL连接也将保持打开状态一段时间.

You are designing your app very wrong. Connections should never stay open for any longer than a single set of queries (that is, the queries needed for a single operation). Don't worry, there is no performance issue as SqlConnection internally pools connections based on connection string. So even if you open and close a connection, the REAL connection will stay open for a period of time.

此外,在内部,如果连接已关闭,则池管理器将在需要时重新打开它,因此您不必担心.

What's more, internally, if the connection is closed, then the pooler will re-open it when needed, so you don't have to worry about it.

严重的是,在使用连接时只需打开和关闭它们即可.那就是它应该起作用的方式.

Seriously, just open and close your connections as you use them. That's how it's supposed to work.

仅供参考,关闭连接的原因是内部连接池管理器将收回"已打开很长时间的连接.因此,通过保持连接打开来进行的工作就是与连接池战斗.

FYI, the reason the connections are closed is that the internal connection pooler will "reclaim" connections that have been open for a long time. So what you're doing by keeping the connections open is fighting the connection pooler.

这篇关于强制SqlConnection打开指定的持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆