简体   繁体   English

检查是否存在与数据库asp.net/c#的打开连接

[英]Check if there's a open connection to database asp.net/c#

Everytime my application runs a stored procedure it does something like this: 每次我的应用程序运行存储过程时,它都会执行以下操作:

using (DbBase conn = new DbBase())
{      
    //call sproc
}

the DBBase() opens the connection with a LINQ DataContext . DBBase()打开与LINQ DataContext的连接。

What I wanted to know, if there's a way to know if a connection has already been opened, and use that instead of opening a new one . 我想知道的是,如果有办法知道连接是否已经打开,并使用它而不是打开一个新连接 That verification should be done inside the DbBase() constructor that goes like this: 该验证应该在DbBase()构造函数内完成,如下所示:

ClientDB = new ClientDBDataContext([ConnectionString from web.config]);

Thank you 谢谢

You look at the State property of any DBConnection object, and it will tell you if it's open, closed, connecting, executing, fetching or broken . 您查看任何DBConnection对象的State属性,它将告诉您它是打开,关闭,连接,执行,提取还是已损坏

By utilizing the using{ } statement though, you're guaranteed that the connection is being closed when the object goes out of scope. 但是,通过使用using{ }语句,可以确保在对象超出范围时关闭连接。

使用使用的using是,这是你不必担心的事情类型。

I wouldn't worry about it (unless you've profiled it or something). 我不担心它(除非你对它有所描述)。 With connection pooling, opening a new connection can be very cheap. 使用连接池,打开新连接可能非常便宜。 If there is a problem then you might want to look at changing the number of connections in the pool ( http://www.15seconds.com/issue/040830.htm ) 如果出现问题,您可能需要查看更改池中的连接数( http://www.15seconds.com/issue/040830.htm

I don't know about DBase, but the Sql Server provider at least already does this for you. 我不知道DBase,但Sql Server提供程序至少已经为你做了这个。 It uses connection pooling in the background to re-use existing connections where possible. 它在后台使用连接池来尽可能重用现有连接。

With connection pooling in place (The default - unlkess you have explicitly done something to turn it off) this is not an issue. 有了连接池(默认 - 你已经明确地做了一些事情来关闭它),这不是问题。 Let the connection pooling code handle this. 让连接池代码处理这个。 Closing the connection then, actually only releases it back to the pool to be reused. 然后关闭连接,实际上只将其释放回池中以便重用。 Only if there are none in the pool will a new one get created (and opened) for you. 只有在池中没有,才会为您创建(并打开)新的。 Good you are using the using statement. 你使用using语句很好。 This ensures that the conection will be released back to the pool for reuse (NOT closed) as doon as this code snippet is done with it. 这确保了连接将被释放回池中以便重复使用(未关闭),因为此代码片段已完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM